-1

I have an array of objects

[
{name: 'hello', children: [{name: 'a'}, {name: 'b'}], 
{name: 'world', children: [{name: 'c'}, {name: 'd'}],
]

What is the most effective way to turn this array into this by using array methods?

[{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}]

I've tried using map and filter but the subelements were still in chunks. Thanks in advance.

2
  • What does filter have to do with this? That's for selecting array elements that meet a condition. Commented May 19, 2021 at 23:05
  • Use reduce() and array concatenation (either with concat() or [...array1, ...array2]) Commented May 19, 2021 at 23:06

1 Answer 1

-1

You can achieve this result using reduce and destructuring the array.

const arr = [
  { name: "hello", children: [{ name: "a" }, { name: "b" }] },
  { name: "world", children: [{ name: "c" }, { name: "d" }] },
];

const result = arr.reduce((acc, { children }) => {
  return [...acc, ...children];
}, []);

console.log(result);

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

3 Comments

Please look for duplicates before answering. You appear to be answering every [javascript] question that comes along, whether it's been answered before or not.
@HereticMonkey I'll take care next time. Thanks. But how would I know that it is a duplicate question... I mean first I've to check whether a question already asked or not then if not I will answer it. Till someone has already answered that question. Just curious to know.
I'm not sure I follow. The duplicate was asked and answered 2 years ago. A simple search for "concatenate array properties of array of objects into one array" found that duplicate quickly. Even a search for "site:stackoverflow.com How to get array of elements of a subarray in javascript" (the title) brings up around 9,000 hits. Stack Overflow is meant to help the asker, yes, but more so to help everyone who comes with the same question. By consolidating the questions to a single one, we do both. Spending a little extra time to find the right duplicate helps the asker and future askers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.