How to find the difference between two arrays
Short answer
Keep the elements of the first array that are not in the second:
const all = ['a', 'b', 'c', 'd'];
const done = ['b', 'd'];
console.log(all.filter((item) => !done.includes(item)).join(', '));Output:
a, cIn either array
The symmetric difference is the elements that are in only one of the two arrays:
const a = [1, 2, 3];
const b = [2, 3, 4];
const diff = [...a.filter((x) => !b.includes(x)), ...b.filter((x) => !a.includes(x))];
console.log(diff.join(', '));Output:
1, 4Set methods
Sets have ready methods difference() and symmetricDifference():
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...a.difference(b)].join(', '));
console.log([...a.symmetricDifference(b)].join(', '));Output:
1
1, 4What was added and removed
Comparing an old and a new list gives both changes:
const before = ['anna', 'oleg', 'ivan'];
const after = ['anna', 'ivan', 'maria'];
console.log('added:', after.filter((x) => !before.includes(x)).join(', '));
console.log('removed:', before.filter((x) => !after.includes(x)).join(', '));Output:
added: maria
removed: olegCommon mistake
The order of arguments matters: the difference of a and b is not the same as the difference of b and a:
const a = [1, 2, 3];
const b = [2, 3, 4];
console.log(a.filter((x) => !b.includes(x)).join(), b.filter((x) => !a.includes(x)).join());Output:
1 4Functions used in this recipe
- Array.prototype.filter — Creates a new array from the elements that pass a test.
- Array.prototype.includes — Checks whether an array contains a value.
- Set — A collection of unique values.