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:
451 chars14 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