0

what's the cleanest way to flatten an array of objects that have this type interface:

Interface {
 Item: Item,
 SubItems: Array<Item>
}

example of an array:

    myArray = [
{Item: {id: "bla1"}, SubItems: [{id: "bla2"}, {id: "bla3"}, {id: "bla4"}]}, 
{Item: {id: "bla5"}, SubItems: [{id: "bla6"}, {id: "bla7"}, {id: "bla8"}]}
]

the end result should be a single array of all these same type objects, and ordered like this:

first object -> Item -> SubItems
second object -> Item -> SubItems

so in my example I should have this:

flattenedArray = [{id: "bla1"}, {id: "bla2"}, {id: "bla3"}, {id: "bla4"}, ...]
2
  • Possible duplicate of flatten javascript array of objects Commented Oct 2, 2018 at 12:45
  • read that thread, but the answer I was given here seems much more cleaner and elegant! Commented Oct 2, 2018 at 12:46

1 Answer 1

1
myArray.map(val => [val.Item, ...val.SubItems]).reduce((acc, cur) => [...acc, ...cur])
Sign up to request clarification or add additional context in comments.

2 Comments

works perfectly, would you mind explaning me quickly the reduce part? I read what it does but honestly didn't quite get it! thank you anyway for the answer
reduce iterates over your array, and executes a special function that takes an accumulator and returns a new accumulator, that is passed to the next function execution. All you have to do is to copy the previous values with ...acc and add the new ones with ...cur

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.