To find the difference between two JavaScript arrays—elements present in arrayA that do not appear in arrayB (A \ B) without mutating either input—convert arrayB into a Set (const exclude = new Set(arrayB);) and filter arrayA with arrayA.filter((item) => !exclude.has(item)). Using a Set gives O(1) average membership checks and O(n + m) overall time complexity instead of O(n * m) with nested includes() calls, and handles NaN cleanly via SameValueZero equality.


1. One-Way Difference (A - B) Using a Set

Filter arrayA against a Set built from arrayB to return elements unique to arrayA while preserving their original order:

// Return elements in `source` that are not present in `excluded`
function arrayDifference(source, excluded) {
  if (!Array.isArray(source) || !Array.isArray(excluded)) {
    throw new TypeError("Expected both source and excluded to be arrays.");
  }

  const excludedSet = new Set(excluded);
  return source.filter((item) => !excludedSet.has(item));
}

// Example usage:
const assignedIds = [101, 102, 103, 104, 102];
const completedIds = [102, 104];

console.log(arrayDifference(assignedIds, completedIds));
// [101, 103] (keeps duplicates present in `assignedIds` unless deduplicated)
  • Non-mutating and fast: Neither source nor excluded is modified, and Set.prototype.has() keeps lookup time fast even for large lists.
  • Duplicates in source: .filter() keeps repeated elements from arrayA that are not in arrayB; wrap in Array.from(new Set(...)) if you also want unique results.

2. Symmetric Difference (Elements in Either Array, Not Both)

When you want items that appear in arrayA or arrayB, but not in both ((A \ B) ∪ (B \ A)), combine both one-way differences:

// Return elements present in `a` or `b`, but not in both arrays
function symmetricDifference(a, b) {
  if (!Array.isArray(a) || !Array.isArray(b)) {
    throw new TypeError("Expected both arguments to be arrays.");
  }

  const setA = new Set(a);
  const setB = new Set(b);

  const onlyInA = a.filter((item) => !setB.has(item));
  const onlyInB = b.filter((item) => !setA.has(item));

  return [...onlyInA, ...onlyInB];
}

// Example usage:
console.log(symmetricDifference(["read", "write", "audit"], ["write", "deploy"]));
// ["read", "audit", "deploy"]
  • Order preserves source appearance: Items exclusive to a appear first, followed by items exclusive to b.
  • SameValueZero matching: Works predictably for primitives and NaN, while objects match only by exact reference.

3. Array of Objects Difference by Key Selector

Because Set compares objects by reference ({ id: 1 } !== { id: 1 }), compare objects by a key selector (such as item => item.id) when finding differences between object arrays:

// Find objects in `primary` whose selected key is not present in `secondary`
function differenceByKey(primary, secondary, keySelector) {
  if (!Array.isArray(primary) || !Array.isArray(secondary) || typeof keySelector !== "function") {
    throw new TypeError("Expected primary and secondary arrays and a keySelector function.");
  }

  const secondaryKeys = new Set(secondary.map((item) => keySelector(item)));
  return primary.filter((item) => !secondaryKeys.has(keySelector(item)));
}

// Example usage:
const currentUsers = [
  { id: 1, name: "Amina" },
  { id: 2, name: "Bilal" },
  { id: 3, name: "Danish" }
];
const activeUsers = [{ id: 2, name: "Bilal" }];

console.log(differenceByKey(currentUsers, activeUsers, (user) => user.id));
// [{ id: 1, name: "Amina" }, { id: 3, name: "Danish" }]
  • Reference gotcha avoided: Two distinct object literals with identical fields won’t falsely look different when compared by a stable ID or key.
  • Explicit error handling: Validates array and selector inputs upfront rather than failing silently or throwing cryptic errors later.