Here are five ways to check if an array contains an element in JavaScript:
- Using array.includes() method
- Using array.indexOf() method
- Using array.some() method
- Using the array.find() method
- Using the array.findIndex() method
Method 1: Using the Array.includes()
The includes() method is used to check whether an array contains a specified element.
Example
const main_array = [11, 21, 18, 19, 46];
console.log(main_array.includes(19))
Output
true
That means 19 is there in the main_array. Now, let’s see a scenario where an array does not contain an element.
const main_array = [11, 21, 18, 19, 46];
console.log(main_array.includes(30))
Output
false
Method 2: Using the Array.indexOf() method
The indexOf() method is used to find the index of the first occurrence of a specified element in an array. It can help you determine if an array contains an element or not.
Example
const main_array = [11, 21, 18, 19, 46];
const index = main_array.indexOf(19);
console.log(index)
Output
3
You can see that element 19 exists on the 3rd index of the array.
Let’s check a scenario where an element does not exist in the array.
const main_array = [11, 21, 18, 19, 46];
const index = main_array.indexOf(30);
console.log(index)
Output
-1
That means an array does not contain an element. It returns -1 when it cannot find an element in the array.
Method 3: Using the Array.some() method
The some() method is a built-in function used to check if at least one element in an array passes a test implemented by a provided function.
Example
const main_array = [11, 21, 18, 19, 46];
const isArrayContains = main_array.some(item => item === 19);
console.log(isArrayContains)
Output
true
Let’s check a scenario where an array does not include an element.
const main_array = [11, 21, 18, 19, 46];
const isArrayContains = main_array.some(item => item === 30);
console.log(isArrayContains)
Output
false
Method 4: Using the Array.find() method
The find() method is used to get the value of the first element in an array that satisfies a given condition.
Example
const main_array = [11, 21, 18, 19, 46];
const isArrayContains = main_array.find(item => item === 19);
console.log(isArrayContains)
Output
19
If the array does not contain the element, it returns undefined.
const main_array = [11, 21, 18, 19, 46];
const isArrayContains = main_array.find(item => item === 30);
console.log(isArrayContains)
Output
undefined
Method 5: Using the Array.findIndex() method
The findIndex() method retrieves the index of the first element in an array that satisfies a given condition.
Example
const main_array = [11, 21, 18, 19, 46];
const isArrayContains = main_array.findIndex(item => item === 19);
console.log(isArrayContains)
Output
3
If the element does not exist in the array, the method returns -1 as an output.
const main_array = [11, 21, 18, 19, 46];
const isArrayContains = main_array.findIndex(item => item === 30);
console.log(isArrayContains)
Output
-1