Check if Arrays contain Common Elements in JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Check if Arrays contain common Elements using Array.includes() #

To check if two arrays contain common elements:

  1. Use the Array.some() method to iterate over the first array.
  2. Check if each element is contained in the second array.
  3. If there is at least 1 common element, the Array.some() method will return true.
index.js
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.

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

Check if Arrays contain common Elements using Array.indexOf() #

To check if two arrays contain common elements:

  1. Use the Array.some() method to iterate over the first array.
  2. Use the Array.indexOf() method to check if each element is contained in the second array.
  3. If the Array.indexOf() method returns a value other than -1, the arrays contain common elements.
index.js
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.

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.