How can I get the result from arr1 and arr2, When the ID matches I need to copy the content from arr1

41 Views Asked by At

How can I get the result from arr1 and arr2, When the ID matches I need to copy the content from arr1

 const arr1 = [
     { id: 1, name: "omar" },
     { id: 2, name: "laith" },
     { id: 3, name: "aref" },
    ]
    
     const arr2 = [
     { id: 1, rating: "good" },
     { id: 2, rating: "very good" },
     { id: 2, rating: "very good" },
     { id: 3, rating: "Excellence" },
     { id: 3, rating: "Excellence" },
    ]
    
     //expected output
     const result = [
     { id: 1, rating: "good", name: "omar" },
     { id: 1, rating: "good", name: "omar" },
     { id: 2, rating: "very good", name: "laith" },
     { id: 3, rating: "Excellence", name: "aref" },
     { id: 3, rating: "Excellence", name: "aref" },
    ]
2

There are 2 best solutions below

0
Sachila Ranawaka On

use reduce with filter

const arr1 = [ { id: 1, name: "omar" }, { id: 2, name: "laith" }, { id: 3, name: "aref" }, ];

const arr2 = [ { id: 1, rating: "good" }, { id: 2, rating: "very good" }, { id: 2, rating: "very good" }, { id: 3, rating: "Excellence" }, { id: 3, rating: "Excellence" }, ];


const result = arr1.reduce((acc,item) => {
    const list = arr2.filter(i => i.id === item.id)
    
    return [...acc, ...list.map(i => ({id: i.id,rating:i.rating, name: item.name}))]
}, [])

console.log(result)

0
IT goldman On

Basically with a loop. Actually 2. Using a temporary object (result) as dictionary (or map) we can make it efficient searching for a match to each id. This is of complexity O(n) basically.

const arr1 = [ { id: 1, name: "omar" }, { id: 2, name: "laith" }, { id: 3, name: "aref" }, ];

const arr2 = [ { id: 1, rating: "good" }, { id: 2, rating: "very good" }, { id: 2, rating: "very good" }, { id: 3, rating: "Excellence" }, { id: 3, rating: "Excellence" }, ];

var result = {}
arr1.forEach(function(item1) {
  result[item1.id] = item1;
});
arr2.forEach(function(item2) {
  result[item2.id] = (result[item2.id] || item2)
  result[item2.id]['rating'] = item2.rating
})

result = Object.values(result)
console.log(result)