Skip to content
Advertisement

How to map an array of objects in to a different one based on criteria? [closed]

How to map an array of objects in to a different one based on criteria?

How to convert the following array of questions in to expected array?

JavaScript

This is the expected array of results.

JavaScript

So the idea is to have a sub array called answers in to which we push the in-between items with type === 'answer'.

So the answers should be pushed to the index n-1 with type === 'question' till the next item with type type === 'question' is encountered. If there are no answers in-between then keep the array empty.

Basicallly we look for the index and type

Update

So the way I tried was I created an array containing the indices. And each time I looped through I looked for the next maximum index and it’s type. Later based on that I tried copying the in-between indices to the previous index.

Advertisement

Answer

Just imagine how you would filter it as a person and then use the same way for the code.

  1. You would definitely check all the elements in that array, so you need to use a loop, and then just filter and push it into the new ‘expected’array.

This is how I would do it.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement