In this article, we will learn how to check if multiple values exist within a given array.
Problem : Suppose we have two arrays,
array1= [‘one’, ‘two’, ‘three’] and
array2= [‘one’, ‘two’, ‘three’, ‘four’, ‘five’, ‘six’] .
And now we have to check whether all the elements in array1 exist in array2.
Solution :
The solution to this problem can be obtained using different JavaScript methods like includes(), every(), and indexOf().
The includes()
method checks if a particular value exists in an array and returns true or false as appropriate.
Syntax:
includes(searchElement)
The every()
method executes a function on every item in an array and returns true if the condition returns true for all the items.
Syntax:
every((element) => { /* ... */ } )
Program to check whether multiple values exist in a given JavaScript Array
const array1= ['one', 'two', 'three']
const array2= ['one', 'two', 'three', 'four', 'five', 'six']
const containAll = array1.every(item => {
return array2.includes(item);
});
console.log(containAll) // true
In the above code, on each iteration of the item in the every() method, the includes() checks if the item is contained in array2.
Since all the values of array1 exit in array2, we get true
as an output.
Note: If any single value in array1 does not exist in array2, then the includes()
method will return false against it and as a whole, the every()
method will also return false.
IMPORTANT: The includes() method is not supported by Internet Explorer, so you can use the indexOf() method instead.
Check if multiple values exist in an array using indexOf()
The indexOf()
method returns the position of the first occurrence of the value in an array.
Example:
const array1= ['one', 'two', 'three']
const array2= ['one', 'two', 'three', 'four', 'five', 'six']
const containAll = array1.every(item => {
return array2.indexOf(item) !== -1;
});
console.log(containAll) // true
In the above code, on each iteration, the indexOf()
check if the item exits in array2, if present it will return the index of the first occurrence of the item in the array.
If the item does not exist in the array then it returns -1.
Since it does not return -1 , it means all the values exist in the array and so every()
method will return as true
.