Q:

Concat multi-dimensional array into one-dimensional array

I have an array with objects
const nodes = [ { children: [1, 2, 3] }, { children: [1, 2, 3] } ];

I want a new array [ 1, 2, 3, 1, 2, 3 ].
I have tried
nodes.map(node => node.children);

but it gives me [ [ 1, 2, 3 ], [ 1, 2, 3 ] ].
I have tried
[].concat(nodes.map(node => node.children));

but it doesn't work since it is just concatenating [] with [ [ 1, 2, 3 ], [ 1, 2, 3 ] ] which is just [ [ 1, 2, 3 ], [ 1, 2, 3 ] ].

A:

You can do this with 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)

A:

You could use 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; }

