Borislav Hadzhiev
Sun Oct 03 2021·2 min read
Photo by Kalen Emsley
To check if two arrays in JavaScript contain common elements:
Array.some
method on the first array
, passing it a functionsecond array
Array.some
will return true
// Not Supported in IE 6-11 const arr1 = ['pizza', 'cake', 'cola']; const arr2 = ['pizza', 'beer']; const contains = arr1.some(element => { return arr2.includes(element); }); console.log(contains); // 👉️ true
The function we passed to the Array.some method is called for each element of the array.
some
method returns true
, otherwise false
is returned.The arrays in the example have a common element, therefore the
Array.includes
method returns true
, causing the Array.some
method to also return true
.
We can also check if two javascript arrays contain common elements, using
Array.indexOf
, instead of Array.includes
.
indexOf
method takes a value and checks if it's contained in an array. If it is, the index of the element is returned, otherwise -1
is returned.// Supported in IE 9-11 const arr1 = ['pizza', 'cake', 'cola']; const arr2 = ['pizza', 'beer']; const contains = arr1.some(element => { return arr2.indexOf(element) !== -1; }); console.log(contains); // 👉️ true
If the arrays have a common element, then
Array.indexOf
will return the element's index, otherwise it returns -1
.
In the code example, there is a common element between the arrays, therefore the
callback function returns true
and the Array.some
method also returns
true
.