Ask any question about JavaScript here... and get an instant response.
How can I merge two arrays of objects based on a common key without duplicates in JavaScript?
Asked on Nov 13, 2025
Answer
To merge two arrays of objects based on a common key without duplicates, you can use the "reduce" and "map" methods to create a new array that combines both arrays while ensuring unique entries based on the specified key.
<!-- BEGIN COPY / PASTE -->
const array1 = [
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
];
const array2 = [
{ id: 2, name: "Jane" },
{ id: 3, name: "Doe" }
];
const mergedArray = [...array1, ...array2].reduce((acc, current) => {
const x = acc.find(item => item.id === current.id);
if (!x) {
acc.push(current);
}
return acc;
}, []);
console.log(mergedArray);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- This code merges "array1" and "array2" based on the "id" key.
- The "reduce" function iterates over the combined array and checks if an object with the same "id" already exists in the accumulator "acc".
- If an object with the same "id" is not found, the current object is added to the accumulator.
- The result is a merged array without duplicates based on the "id" key.
Recommended Links:
