Check if Arrays contain Common Elements in JavaScript

avatar

Borislav Hadzhiev

Sun Oct 03 20212 min read

banner

Photo by Kalen Emsley

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
index.js
// 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.
index.js
// 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee