Check if Array has all Elements of Another Array - JavaScript

avatar

Borislav Hadzhiev

Sun Oct 03 20212 min read

banner

Photo by pixpoetry

Check if Array has all Elements of Another Array - Array.includes #

To check if a javascript array contains all of the elements of another array:

  1. Call the Array.every method on the first array, passing it a function
  2. The function should check if each element is included in the second array
  3. If the check is successful for all elements, the Array.every method will return true
index.js
// Not Supported in IE 9-11 const arr1 = ['pizza', 'cola']; const arr2 = ['pizza', 'cake', 'cola']; const containsAll = arr1.every(element => { return arr2.includes(element); }); console.log(containsAll); // ๐Ÿ‘‰๏ธ true

The function we pass to the Array.every method is invoked with each element of the array and should return a truthy or falsy value.

If all invocations of the callback function return a truthy value, then the Array.every method returns true, otherwise false is returned.

In the example we use the Array.every method to iterate over the elements of the first array. We check if each value is contained in the second array by using the Array.includes method.

If the callback function we passed to the Array.every method returns a falsy value, then Array.every also returns false.

If the first invocation of the callback function returns a falsy value, then the Array.every method will short circuit and not invoke the callback with the other array elements.

Check if Array has all Elements of Another Array - Array.indexOf #

To check if a javascript array contains all of the elements of another array:

  1. Call the Array.every method on the first array, passing it a function
  2. The function should check if the index of each element is found in the second array
  3. If the check is successful for all elements, the Array.every method will return true
index.js
// Supported in IE 9-11 const arr1 = ['pizza', 'cola']; const arr2 = ['pizza', 'cake', 'cola'] const containsAll = arr1.every(element => { return arr2.indexOf(element) !== -1; }); console.log(containsAll); // ๐Ÿ‘‰๏ธ true
The Array.every method returns true, only if the condition is satisfied for all array elements.

In the code snippet, we've used the Array.every method to iterate over each element of the first array and check if it is contained in the second array.

The Array.indexOf method searches for a value in the array and returns it's index if the value is contained in the array, otherwise returns -1.

In the example above, arr2 contains all of the elements of arr1, therefore the return value of the Array.indexOf method will never be equal to -1, so theArray.every method returns true.
The Array.every method returns false on the first falsy return from the callback function.

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