Skip to content
Advertisement

How to merge two object arrays by adding matching object in as a new field

I have these two arrays:

JavaScript

My goal is to produce this final array:

JavaScript

Basically I want to merge the two goodCars and badCars arrays into one but if the cars exists in both good and badd arrays then I want to add the bad car to the good car array as a new field toCompareWith: {...} (seen above)

I’ve tried using map(), reduce(), for loops, etc. but my brain has hit a wall and I’m not getting any closer.

My attempt:

JavaScript

Answer I went with based on the below marked correct one: ✅

JavaScript

Advertisement

Answer

You shouldn’t use nested loops.

Start by copying goodCars to finalCarList. Then loop over badCars. If the car is in goodCars, add the bad car as the toCompareWith property. Otherwise, push it into finalCarList.

JavaScript

Also, in general you shouldn’t use map() if the callback function doesn’t return anything. If it’s called only for side effects, use forEach().

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