How to find common elements of two arrays
Short answer
Keep the elements of the first array that are also in the second:
const a = [1, 2, 3, 4];
const b = [3, 4, 5];
console.log(a.filter((item) => b.includes(item)).join(', '));Output:
3, 4Large arrays
includes() searches the whole array every time. With a Set, each check is instant:
const a = ['tea', 'milk', 'bread'];
const b = new Set(['bread', 'tea', 'eggs']);
console.log(a.filter((item) => b.has(item)).join(', '));Output:
tea, breadSet methods
Modern environments have intersection() and union() on sets:
const a = new Set([1, 2, 3]);
const b = new Set([2, 3, 4]);
console.log([...a.intersection(b)].join(', '));
console.log([...a.union(b)].join(', '));Output:
2, 3
1, 2, 3, 4Common mistake
If the first array has repeats, the result has them too. Remove duplicates with a Set:
const a = [1, 1, 2];
const b = [1, 2];
console.log(a.filter((item) => b.includes(item)).join(', '));
console.log([...new Set(a.filter((item) => b.includes(item)))].join(', '));Output:
1, 1, 2
1, 2Functions 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.