merge object array without duplicates in javascript

To merge two object arrays without duplicates in JavaScript, you can use the concat() method to combine the arrays, then use the reduce() method to iterate over the combined array and create a new object that contains only the unique objects.

Here's an example code snippet:

const arr1 = [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }];
const arr2 = [{ id: 1, name: 'John' }, { id: 3, name: 'Bob' }];
const mergedArr = arr1.concat(arr2);

const uniqueArr = mergedArr.reduce((acc, curr) => {
  const existingObj = acc.find(obj => obj.id === curr.id);
  if (!existingObj) {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(uniqueArr); // [{ id: 1, name: 'John' }, { id: 2, name: 'Alice' }, { id: 3, name: 'Bob' }]
451 chars
14 lines

In this example, arr1 and arr2 are the two object arrays to be merged. We first use concat() to combine them into a single array called mergedArr.

Then, we use reduce() to iterate over mergedArr and create a new array called uniqueArr. In each iteration, we check if the current object (curr) already exists in the acc array (which starts as an empty array). We search for an existing object with the same id property using the find() method. If we don't find an existing object, we add the current object to the acc array using the push() method.

Finally, we return the acc array after all iterations are complete, which gives us a new array that contains only the unique objects from the original arrays.

gistlibby LogSnag