Skip to content
Advertisement

Match two arrays with same id

const array1 = [{id:1,name: "foo"},{id:2,name:"boo"},{id:3,name:"fob"}]
const array2 = [{id:1, carType: "truck"},{id:2, carType: "sedan"},{id:3,carType: "suv"}]

How to push name from array1 to array2 with matching ids

end result

array3 = [
{id:1, carType: "truck",name: "foo"},
{id:2, carType: "sedan", name: "boo"},
{id:3,carType: "suv",name:"fob"}
]

Advertisement

Answer

Here’s how I’d do it:

const array1 = [{id:1,name: "foo"},{id:2,name:"boo"},{id:3,name:"fob"}]
const array2 = [{id:1, carType: "truck"},{id:2, carType: "sedan"},{id:3,carType: "suv"}]


const indexed = Object.fromEntries(array1.map(o => [o.id, o]))

const combined = array2.map(o => ({...o, ...indexed[o.id]}))

console.log(combined)

i.e. create an object out of one of the arrays, using the id as the key. Then you can map over the 2nd one and use the ‘index’ to quickly look up elements in the first one.

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