javascript - Determine whether an array contains a value
The easiest way to determine whether an array contains a value is to use the Array.prototype.includes()
method. This method checks whether an array contains a certain element and returns true
or false
. For example, the following code will check whether the array arr
contains the value 3
:
const arr = [1, 2, 3, 4, 5];
const containsThree = arr.includes(3);
console.log(containsThree); // true
There are also a few other ways to do this. For example, you can use the Array.prototype.indexOf()
method, which returns the index of the first occurrence of a given element in the array. If the element is not found, the method returns -1
. So if you want to check if an array contains a given value, you can check if the indexOf()
result is not -1
. For example:
const arr = [1, 2, 3, 4, 5];
const indexOfThree = arr.indexOf(3);
const containsThree = indexOfThree !== -1;
console.log(containsThree); // true
Finally, you can also use the Array.prototype.some()
method, which returns true
if at least one element in the array passes the given test. For example:
const arr = [1, 2, 3, 4, 5];
const containsThree = arr.some(el => el === 3);
console.log(containsThree); // true
If you want to check if an array contains multiple values, you can also use the Array.prototype.every()
method, which returns true
if every element in the array passes the given test. For example:
const arr = [1, 2, 3, 4, 5];
const containsOneTwoThree = arr.every(el => [1, 2, 3].includes(el));
console.log(containsOneTwoThree); // true
As you can see, there are a few different ways to determine whether an array contains a value, and it's up to you to decide which one is the most appropriate for your use case.