Check if Array has all Elements of Another Array - JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if Array has all Elements of Another Array #

To check if an array contains all of the elements of another array:

  1. Call the Array.every() method on the first array.
  2. Check if each element in the array is contained in the second array.
  3. If the condition is met for all elements, the array has all elements of the other array.
index.js
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 passed to the Array.every method is invoked with each element of the array and should return a truthy or a falsy value.

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

We used the Array.every method to iterate over the first array. To check if each value is contained in the second array, use 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 short-circuits returning false.

Alternatively, you can use the Array.indexOf() method.

To check if an array contains all of the elements of another array:

  1. Call the Array.every method on the first array.
  2. Check if the index of each element is found in the second array.
  3. If the condition is met for all elements, the array has all elements of the other array.
index.js
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.

We used the Array.every method to iterate over the first array.

On each iteration, we check if the current element is contained in the second array.

The Array.indexOf method returns the index of the provided value in the array. If the value is not found in the array, the method returns -1.

The arr2 array contains all of the elements of arr1, therefore the return value of the Array.indexOf method will never be equal to -1.

After the Array.every() method finishes iterating, it 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.