[英]Store values from multiple arrays into one array (JavaScript/Reactjs)
I have an array, which is having arrays as it's values.我有一个数组,它的值是 arrays。 What I need is an output that is having all array values.我需要的是具有所有数组值的 output。
Note : input array and it's elements(arrays) are not of fixed length.注意:输入数组及其元素(数组)不是固定长度的。
Input :输入:
array =
[
[a,b],
[c,d,e],
[f,g]
]
Output : Output :
[
{
Header : a
Children :
[
{
Header : c
Children :
[
Header : f
]
},
]
},
{
Header : a
Children :
[
{
Header : c
Children :
[
Header : g
]
},
]
},
{
Header : a
Children :
[
{
Header : d
Children :
[
Header : f
]
},
]
},
.
.
.
{
Header : a
Children :
[
{
Header : e
Children :
[
Header : g
]
},
]
},
{
Header : b
Children :
[
{
Header : c
Children :
[
Header : f
]
},
]
},
.
.
.
.
.
{
Header : b
Children :
[
{
Header : e
Children :
[
Header : g
]
},
]
},
]
Basically it is like,基本上是这样的,
[a,c,f],
[a,c,g],
[a,d,f],
[a,d,g],
[a,e,f],
[a,e,g],
[b,c,f],
[b,c,g],
[b,d,f],
[b,d,g],
[b,e,f],
[b,e,g]
I have tried using for loop but couldn't get the desired output.我曾尝试使用 for 循环,但无法获得所需的 output。 Is there any way that we can achieve that result?有什么方法可以达到这个结果吗?
You can create a Cartesian product of the 2D array first.您可以先创建二维数组的笛卡尔积。 Then, use reduceRight
to create a nested object for each array in the Cartesian product然后,使用reduceRight
为笛卡尔积中的每个数组创建一个嵌套的 object
const data = [ ["a", "b"], ["c", "d", "e"], ["f", "g"] ] const cartesian = data.reduce((acc, curr) => acc.flatMap(c => curr.map(n => [].concat(c, n))) ) const tree = arr => arr.reduceRight((acc, Header) => acc? ({ Header, Children: [acc] }): ({ Header }), null) const output = cartesian.map(tree) console.log(JSON.stringify(cartesian)) console.log(output)
function join(arrayOfArrays) {
let current = [[]];
for (let array of arrayOfArrays) {
current = current.flatMap(c=>array.map(a=>[...c, a]));
}
return current;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.