Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
To check if an array contains all of the elements of another array:
Array.every()
method on the first array.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.
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
.
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:
Array.every()
method on the first array.const arr1 = ['pizza', 'cola']; const arr2 = ['pizza', 'cake', 'cola'] const containsAll = arr1.every(element => { return arr2.indexOf(element) !== -1; }); console.log(containsAll); // 👉️ true
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
.