merge two object arrays without duplicates in javascript

To merge two arrays of objects without duplicates in JavaScript, you can use a combination of the concat() and filter() methods.

Here's an example code snippet:

index.tsx
const arr1 = [{id: 1, name: "John"}, {id: 2, name: "Jane"}];
const arr2= [{id: 2, name: "Jane"}, {id: 3, name: "Bob"}];

const mergedArr = arr1.concat(arr2).filter((item, index, self) =>
  index === self.findIndex((t) => (
    t.id === item.id && t.name === item.name
  ))
);

console.log(mergedArr);
// Output: [{id: 1, name: "John"}, {id: 2, name: "Jane"}, {id: 3, name: "Bob"}]
381 chars
12 lines

In this example, we first define two arrays of objects arr1 and arr2. We then use the concat() method to join the two arrays.

Next, we use the filter() method to deduplicate the merged array. The filter() method creates a new array with all elements that pass the test implemented by the provided function. In our case, we use the findIndex() method to ensure that each item in the array is unique based on a combination of id and name properties.

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function, otherwise, it returns -1. If we find an element with the same id and name properties in the self array at another index (different from the current index parameter), then we know it's a duplicate and we filter it out.

Finally, we log the deduplicated mergedArr array to the console.

gistlibby LogSnag