Check if Arrays contain Common Elements in JavaScript


Borislav Hadzhiev

Last updated: Oct 3, 2021


Photo from Unsplash

Check if Arrays contain common Elements - includes #

To check if two arrays in JavaScript contain common elements:

  1. Use the Array.some method on the first array, passing it a function
  2. The function should return whether the element is included in the second array
  3. If there is at least 1 common element, 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.

If at least one invocation of the callback function returns a truthy value, then the 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.

Check if Arrays contain common Elements - indexOf #

We can also check if two javascript arrays contain common elements, using Array.indexOf, instead of Array.includes.

The 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.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.