DifferenceLoading saved progress…

Difference

You have two lists and you want to know what's in the first one that isn't in the second. Think of a "to-do" list minus a "done" list: what's left is the work still ahead. This is the classic set-difference operation, often written as A \ B in math notation, and lodash exposes it as _.difference.

Implement a difference(a, b) function that returns a new array containing every element from a that does not appear in b. The original arrays must not be modified, and the order of elements in a must be preserved in the result.

Signature

function difference(a, b) {
  // returns a new array of items in `a` that are not in `b`
}

Examples

difference([1, 2, 3, 4], [2, 4]);
// → [1, 3]
difference(['a', 'b', 'a', 'c'], ['b']);
// → ['a', 'a', 'c']   // duplicates in `a` are kept

Notes

  • Preserve order — items in the result must appear in the same order they appear in a.
  • Keep duplicates — if a value appears twice in a and not in b, it appears twice in the result.
  • Don't mutate — return a new array; leave a and b untouched.
  • Equality is SameValueZero — the same rule Set.has and Array.includes use. NaN equals NaN, and 0 equals -0.
  • Aim for O(n + m) — a nested scan works but is O(n × m). A Set gets you constant-time lookups.
Loading editor…