JavaScript Code

How to find the index of element in array using JavaScript?


Problem Statement

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');
}



copyright @2022