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

Time:12-07

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" },
    ]

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

Using the Array.prototype.map() method, we can loop through each element of arr2 and use the Array.prototype.find() method to check if the id of the current element in arr2 matches any id in arr1. If it does, we can return a new object with a combination of the matching element from arr1 and the current element from `arr2.

const result = arr2.map(item => {
  const matchingItem = arr1.find(arr1Item => arr1Item.id === item.id);
  return { ...matchingItem, ...item };
});

console.log(result);
  • Related