3

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 ] ].

3 Answers 3

3

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! After reducing, I am removing duplicates with .filter((item, pos, self) => self.indexOf(item) == pos). Does it make sense to do this inside the reduce instead of afterwards with chaining?
you could use Set for unique values.
is it the same as Array.from(new Set(result))?
3

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)

Comments

1

Another way to do this using Array#forEach:

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

Another shorter way is (a little modification to what OP was trying to do):

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.