JavaScript Code


JavaScript Array indexOf()


indexOf() – Index of Specified Element

array.indexOf(element)
array.indexOf(element, start)
  • array is an array of elements in which we need to find the index of specified element.
  • indexOf is the array method name.
  • element is the element to search for in the array.
  • start is an integer, optional value. default value is 0.

indexOf() method returns the index of first occurrence of the element in the array, or returns -1 if the element is not present in the array. If start is passed as second argument to indexOf(), then the search for the element starts from this index start.

Examples

1. Find the index of the element 'cherry' in the array fruits.

let fruits = ['apple', 'banana', 'cherry', 'mango'];
let element = 'cherry';
let 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');
}

2. Find the index of the element 'guava' in the array fruits, given that the element is not present in the array.

let fruits = ['apple', 'banana', 'cherry', 'mango'];
let element = 'guava';
let 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');
}

3. Find the index of the element 'banana' in the array fruits, after a start position of 2.

let fruits = ['apple', 'banana', 'cherry', 'mango'];
let element = 'banana';
let start = 2;
let index = fruits.indexOf(element, start);

if ( index != -1 ) {
    console.log(`index of ${element} in array is ${index}`);
} else {
    console.log('element is not present in array');
}


Copyright @2022