My goal is to merge data from two arrays based on the userId
. The current solution I have only works efficiently with small datasets, but it becomes impractical with larger arrays due to the excessive use of the filter
method. Does anyone have a more efficient approach in mind?
PS: I'm using > 0 ? because sometimes one of the properties is empty.
const data01 = [
{ userId: 0, motorcycles: 'motorcycle01', cars: 'car01' },
{ userId: 1, motorcycles: 'motorcycle02', cars: 'car02' },
{ userId: 2, cars: 'car03' },
{ userId: 3, motorcycles: 'motorcycle04' },
]
items.forEach(
a =>
(
a.motorcylces = data01.filter(b => b.userId === a.userId).length > 0 ? data01.filter(b => b.userId === a.userId)[0].motorcylces : null,
a.cars = data01.filter(b => b.userId === a.userId).length > 0 ? data01.filter(b => b.userId === a.userId)[0].cars : null
)
);
console.log(items)
Expected Output:
[
{
...
motorcycles: 'motorcycle01',
cars: 'cars01'
},
{
...
motorcycles: 'motorcycle01',
cars: 'cars01'
}
]