我有一个数组,它的值是数组。我需要的是具有所有数组值的输出。
注意:输入数组及其元素(数组)不是固定长度的。
输入:
array =
[
[a,b],
[c,d,e],
[f,g]
]
输出:
[
{
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
]
},
]
},
]
基本上就像,
[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]
我尝试过使用 for 循环,但无法获得所需的输出。 有什么方法可以实现这个结果吗?
最佳答案
您可以创建 Cartesian product首先是二维数组。然后,使用 reduceRight
为笛卡尔积中的每个数组创建一个嵌套对象
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)
关于javascript - 将多个数组中的值存储到一个数组中(JavaScript/Reactjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58400283/