@FahadM to JavaScriptEnglish • 6 days ago

How do you merge two JavaScript arrays and remove all duplicate items?

message-square
0
1
How do you merge two JavaScript arrays and remove all duplicate items?
@FahadM to JavaScriptEnglish • 6 days ago

The fastest, cleanest way to merge two JavaScript arrays and remove duplicates for primitive values is spread syntax (...) combined with new Set(...), converted back to an array with [...] (or Array.from(...)). Set preserves insertion order and runs in roughly linear time, while object arrays need a key-based deduplication step because two distinct { id: 1 } objects are not equal by reference.


1. Merging and Deduplicating Primitive Arrays with Set

Combine both arrays inside a Set so duplicate primitives are automatically dropped while keeping the first occurrence order:

// Merge two primitive arrays and remove duplicates while preserving order
function mergeUniquePrimitives(firstArray, secondArray) {
  return [...new Set([...firstArray, ...secondArray])];
}

const frontendTags = ["js", "dom", "async", "js"];
const backendTags = ["node", "async", "sql", "js"];

console.log(mergeUniquePrimitives(frontendTags, backendTags));
// ["js", "dom", "async", "node", "sql"]
  • [...arrayA, ...arrayB]: Shallow-merges both arrays into a single sequence without mutating either original array.
  • new Set(...): Filters out duplicate values using SameValueZero equality (including NaN matching NaN).
  • [...set]: Converts the Set back into a standard Array with full array methods like .map(), .filter(), and .length.

2. Deduplicating Arrays of Objects by a Unique Key

Because Set compares objects by reference, { id: 1 } and { id: 1 } look different to a Set—use a Map keyed by a unique property (such as id) to merge and deduplicate objects cleanly:

// Merge two object arrays and deduplicate by a key (e.g., "id")
function mergeUniqueByKey(firstList, secondList, key) {
  const mergedMap = new Map();

  for (const item of [...firstList, ...secondList]) {
    const identifier = item[key];
    if (!mergedMap.has(identifier)) {
      mergedMap.set(identifier, item);
    }
  }

  return [...mergedMap.values()];
}

const usersA = [{ id: 1, name: "Ali" }, { id: 2, name: "Sara" }];
const usersB = [{ id: 2, name: "Sara Duplicate" }, { id: 3, name: "Usman" }];

console.log(mergeUniqueByKey(usersA, usersB, "id"));
// [{ id: 1, name: "Ali" }, { id: 2, name: "Sara" }, { id: 3, name: "Usman" }]
  • Map keeps first-seen entries: Checking !mergedMap.has(identifier) preserves the first item; omitting that check lets later items overwrite earlier ones.
  • Immutability preserved: Neither input array is modified when building the new deduplicated array.

3. Common Traps to Avoid

Deduplicating arrays seems straightforward, but a few subtleties trip up developers:

  • Expecting new Set([{ id: 1 }, { id: 1 }]) to deduplicate objects: Separate object literals have different references in memory, so Set keeps both unless you deduplicate by a key or canonical identifier.
  • Mutating input arrays unintentionally: Methods like .push() mutate the target array if you pass arr1.push(...arr2) directly instead of spreading into a new array.
  • Order assumptions: Set and Map preserve insertion order, so the order of your merged arrays determines which duplicate wins or appears first.

TL;DR: Use [...new Set([...arr1, ...arr2])] to merge and deduplicate primitive arrays cleanly, and use a Map keyed by a unique property when merging arrays of objects.

Are you merging primitive values (like strings or numbers) or arrays of objects where you need to match by a specific field like id?