Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
To check if two arrays contain common elements:
Array.some()
method to iterate over the first array.Array.some()
method will return
true
.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 gets called with each element of the array.
some()
method returns true
, otherwise, false
is returned.The arrays in the example have a common element, so the
Array.includes
method returns true
, causing the Array.some()
method to also return true
.
Alternatively, you can use the indexOf()
method.
To check if two arrays contain common elements:
Array.some()
method to iterate over the first array.Array.indexOf()
method to check if each element is contained in the
second array.Array.indexOf()
method returns a value other than -1
, the arrays
contain common elements.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, so the
callback function returns true
and the Array.some()
method also returns
true
.