Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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

Large 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, bread

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

Common 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, 2

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.