如何从具有动态长度的多维数组生成新的连接多维数组



如何翻转数组数组b

?或者我如何生成一个矩阵式多维数组基于数组a下面呢?

条件:1。数组a的长度为动态。2. 数组a中每个元素的长度dynamictoo

const a = [
['red', 'blue'],
['small', 'medium', 'large'],
]
const b = [
['red', 'small'],
['red', 'medium'],
['red', 'large'],
['blue', 'small'],
['blue', 'medium'],
['blue', 'large'],
]

示例2:

const a = [
['quadcore'],
['4GB', '8GB'],
['black', 'grey'],
]
const b = [
['quadcore', '4GB', 'black'],
['quadcore', '4GB', 'grey'],
['quadcore', '8GB', 'black'],
['quadcore', '8GB', 'grey'],
]

您需要遍历数组的数组并逐个压入它。下面是代码片段:

function print(arr)
{
let n = arr.length;
let result = [];
let indices = new Array(n);
for(let i = 0; i < n; i++)
indices[i] = 0;
while (true)
{
// Print current combination
let tmp = [];
for(let i = 0; i < n; i++){
tmp.push(arr[i][indices[i]]);   
}
result.push(tmp);
let next = n - 1;
while (next >= 0 && (indices[next] + 1 >=
arr[next].length))
next--;
// No such array is found so no more
// combinations left
if (next < 0)
break;
// If found move to next element in that
// array
indices[next]++;
// For all arrays to the right of this
// array current index again points to
// first element
for(let i = next + 1; i < n; i++)
indices[i] = 0;
}
return result;
}
const a = [
['quadcore'],
['4GB', '8GB'],
['black', 'grey'],
];
console.log(print(a));

引用:https://www.geeksforgeeks.org/combinations-from-n-arrays-picking-one-element-from-each-array/

一个简单的reduce()可以用来解决你的问题。

const arr = [
["red", "blue"],
["small", "medium", "large"],
];
const output = arr.reduce((acc, cur) => {
const store = [];
for (const a of acc) {
for (const c of cur) {
if (Array.isArray(a)) {
store.push([...a, c]);
} else {
store.push([a, c]);
}
}
}
return store;
});
console.log(output);

最新更新