Skip to content
Advertisement

Merge 2 arrays of object based on specific object key

I have 2 arrays which is contains same id with different value (inside selected) My goal is to merge both become 1 array.

When I use spread operator like this:

JavaScript

It comes the data being override

First array

JavaScript

Second array

JavaScript

How can I make both of arrays become 1 ? the expected result:

JavaScript

What am I doing wrong in the above?

Advertisement

Answer

You can use Array.reduce() to combine the two arrays into one.

We start by concatenating and then grouping by id. For each item with the same ids we combine the selected arrays.

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