Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, c

In 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, 4

Set 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, 4

What 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: oleg

Common 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 4

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.