merge two object arrays with only unique entries in javascript

We can use the Set object in JavaScript to achieve the merging of two object arrays with only unique entries. With the help of the Set object, we can first merge the two arrays and then get only the unique entries. Here is the code to achieve this:

index.tsx
const arr1 = [{id: 1, name: 'John'}, {id: 2, name: 'Sam'}];
const arr2 = [{id: 1, name: 'John'}, {id: 3, name: 'Alex'}];

const merged = [...arr1, ...arr2];

const unique = Array.from(new Set(merged.map(JSON.stringify))).map(JSON.parse);

console.log(unique); // Output: [{id: 1, name: 'John'}, {id: 2, name: 'Sam'}, {id: 3, name: 'Alex'}]
340 chars
9 lines

In the above code, we first defined two arrays arr1 and arr2 with some objects. Then, we merged them using the spread (...) operator and stored them in a new array called merged.

Next, we used the Set constructor to create a new set containing only unique entries. The map function is used to map the array of objects to an array of their stringified versions using JSON.stringify. Then, Array.from is used to convert the set object to an array. Finally, we mapped those stringified objects back to objects using JSON.parse.

In the end, we logged the unique array to the console which contains only the unique entries.

gistlibby LogSnag