Find the index of element in array in JavaScript
In this tutorial, you are given an array and a search element. Write a JavaScript program to find the index of first occurrence of the search element in the array.
Solution
To find the index of first occurrence of given search element in the given array of elements using JavaScript, call Array method indexOf() on the array, and pass the search element as argument. If the search element is present in the array, then indexOf()
returns the index, else indexOf()
returns -1
.
Program
1. Find the index of the element 'cherry'
in the array fruits
.
fruits = ['apple', 'banana', 'cherry', 'mango'];
element = 'cherry';
index = fruits.indexOf(element);
if ( index != -1 ) {
console.log(`index of ${element} in array is ${index}`);
} else {
console.log('element is not present in array');
}