Check if Multiple Values exist in Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if Multiple Values exist in Array #

To check if multiple values exist in an array:

  1. Use the every() method to iterate over the array of values.
  2. On each iteration check if the value is contained in the other array.
  3. If all values exist in the array, the every method will return true.
index.js
const arr = ['one', 'two', 'three', 'four']; const values = ['one', 'two']; const multipleExist = values.every(value => { return arr.includes(value); }); console.log(multipleExist); // 👉️ true

The function we passed to the Array.every method gets called with each element until it returns a falsy value or iterates over the entire array.

On each iteration, we use Array.includes method to check if the value is contained in the other array.

If even a single value is not contained in the array, the includes method returns false, which causes the every method to short-circuit also returning false.

Here is a reusable function that that achieves the same result.

index.js
function multipleExist(arr, values) { return values.every(value => { return arr.includes(value); }); } // 👇️ true console.log(multipleExist([1, 2, 3], [1, 3])); // 👇️ false console.log(multipleExist([1, 2, 3], [1, 10])); // 👉️ false

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

To check if multiple values exist in an array:

  1. Use the every() method to iterate over the array of values.
  2. On each iteration, use the indexOf method to check if the value is contained in the other array.
  3. If all values exist in the array, the every method will return true.
index.js
const arr = ['one', 'two', 'three', 'four']; const values = ['one', 'two']; const multipleExist = values.every(value => { return arr.indexOf(value) !== -1; }); console.log(multipleExist); // 👉️ true

This is very similar to our previous example. However, this time we used the Array.indexOf method.

The indexOf method checks if a value is contained in an array and returns the index of the first occurrence of the value in the array.

If the value is not contained in the array, the method returns -1.

If the indexOf method does not return -1, then the value is contained in the array.

Here is a reusable function that that achieves the same result.

index.js
function multipleExist(arr, values) { return values.every(value => { return arr.indexOf(value) !== -1; }); } // 👇️ true console.log(multipleExist([1, 2, 3], [1, 2])); // 👇️ false console.log(multipleExist([1, 2, 3], [4, 2]));

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.