skip to Main Content

consider below 2 array of objects, say arr1 and arr2.
based on id, if any new item exist in arr2 copy item to arr1 and remove item from arr1 if that item not present in arr2.
Tried something like this,

const arr1 = [
  {name: "name1", id: 1},
  {name: "name2", id: 2},
  {name: "name3", id: 3}
];
    
const arr2 = [
  {name: "name1", id: 1},
  {name: "name2", id: 4},
  {name: "name3", id: 3}
];

const array1 = arr2.filter((val) => {
  return arr1.find((val2) => {
    const arr = [];
    if (!arr1.includes(val.id)) {
      arr.push(val);
    }
  });
});

console.log(array1)

required output

output = `[ 
{name: "name1", id: 1},
{name: "name3", id: 3},
{name: "name2", id: 4} 
]`

2

Answers


  1. EDIT:

    Reduce method, based on "id" may be used but note that ordering does not comply with your expected result as commented below by Hao Wu

    const arr1 = [
          {name: "name1", id: 1},
          {name: "name2", id: 2},
          {name: "name3", id: 3}
        ];
    
        const arr2 = [
          {name: "name1", id: 1},
          {name: "name2", id: 4},
          {name: "name3", id: 3}
        ];
    
    let output = arr2.reduce((a,b) => {
        let a1 = arr1.find(e => e.id === b.id) || {};
        return a.concat(Object.assign(a1, b));
    },[]);
    
    console.log(output)
    Login or Signup to reply.
  2. You can use below code:
    const arr1 = [
      { name: "name1", id: 1 },
      { name: "name2", id: 2 },
      { name: "name3", id: 3 }
    ];
    
    const arr2 = [
      { name: "name1", id: 1 },
      { name: "name2", id: 4 },
      { name: "name3", id: 3 }
    ];
    
    var idsInArr2 = new Set(arr2.map(item => item.id));
    
    // Remove items from arr1 that are not in arr2
    var updatedArr1 = arr1.filter(item => idsInArr2.has(item.id));
    
    // Create a set of IDs from updatedArr1 for quick lookup
    var idsInUpdatedArr1 = new Set(updatedArr1.map(item => item.id));
    
    // Add items to arr1 that are in arr2 but not in updatedArr1
    arr2.forEach(item => {
      if (!idsInUpdatedArr1.has(item.id)) {
        updatedArr1.push(item);
      }
    });
    
    console.log(updatedArr1);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search