To check if an element is in an array or not, you can use the includes()
method. The includes()
method is part of ES6 and it’s a perfect method to check the existence of an element in an array.
The includes()
method returns true if the element exists in the array otherwise it returns false.
See the following example:
const fruits = ['apple', 'banana', 'mango', 'orange']; fruits.includes('banana'); // 👉 true fruits.includes('grapes'); // 👉 false fruits.includes('orange'); // 👉 true
By default, the includes()
method searches for the element in the entire array. But you can also specify the starting index as a second parameter from where the search for the element should happen.
See the following example:
const fruits = ['apple', 'banana', 'mango', 'orange']; fruits.includes('banana'); // 👉 true (Searches in entire array) fruits.includes('banana', 2); // 👉 false (Search starts from index 2)
Check if an Element is in an Array using indexOf() Method
Another simplest way to check if an element is present in an array or not is to use the Array.indexOf()
method. The indexOf()
method returns the index of the element if it is found in the array otherwise it returns -1.
See the following example:
const fruits = ['apple', 'banana', 'mango', 'orange']; console.log(fruits.indexOf('banana')); // Output: 1 console.log(fruits.indexOf('grapes')); // Output: -1 console.log(fruits.indexOf('orange')); // Output: 3
The indexOf()
method only returns the index of the first occurrence of the searched element. This means, if the searched element is present at multiple places in the array, only the index of the first matching element will be returned.
See this example:
const fruits = ['apple', 'banana', 'mango', 'banana', 'banana']; console.log(fruits.indexOf('banana')); // Output: 1
By default, the indexOf()
method searches the element in the entire array. But, just like the includes()
method, we can also pass a second parameter to the indexOf()
method as a starting index from where the search should happen in the array.
See this example:
const fruits = ['apple', 'banana', 'mango', 'orange']; console.log(fruits.indexOf('banana')); // Output: 1 (Searches in the entire array) console.log(fruits.indexOf('banana', 2)); // Output: -1 (Search starts from index 2)