将多维数组合并为一维数组

3

我有一个包含对象的数组

const nodes = [ { children: [1, 2, 3] }, { children: [1, 2, 3] } ];

我想要一个新的数组[ 1, 2, 3, 1, 2, 3 ]

我已经尝试过

nodes.map(node => node.children);

但是它给我返回了[ [ 1, 2, 3 ], [ 1, 2, 3 ] ]

我已经尝试过

[].concat(nodes.map(node => node.children));

但它不起作用,因为它只是将[][[1,2,3],[1,2,3]]连接起来,这只是[[1,2,3],[1,2,3]]

3个回答

3
你可以使用 Array#reduce 来完成这个任务。

const nodes = [ { children: [1, 2, 3] }, { children: [1, 2, 3] } ];

var result = nodes.reduce(function(r, o) {
  r = r.concat(o.children);
  return r;
}, []);

console.log(result)


3
你可以使用 Array#reduce

const nodes = [ { children: [1, 2, 3] }, { children: [1, 2, 3] } ],
      result = nodes.reduce((r, node) => r.concat(node.children), []);

console.log(result);
console.log([... new Set(result)]); // for unique values
.as-console-wrapper { max-height: 100% !important; top: 0; }


谢谢!在缩小后,我使用.filter((item, pos, self) => self.indexOf(item) == pos)来删除重复项。这样做是否有意义,可以在reduce内部完成,而不是之后进行链式操作? - mortensen
1
你可以使用Set来获取唯一值。 - Nina Scholz
它和 Array.from(new Set(result)) 是一样的吗? - mortensen

1

使用Array#forEach的另一种方法:

const nodes = [ { children: [1, 2, 3] }, { children: [1, 2, 3] } ]
final = []
nodes.forEach(x => final = final.concat(x.children))
console.log(final)

另一种更短的方法是(对OP尝试做的稍作修改):

const nodes = [ { children: [1, 2, 3] }, { children: [1, 2, 3] } ];
var result = [].concat.apply([], nodes.map(x => x.children))
console.log(result);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接