JavaScript Code


JavaScript Array lastIndexOf()


lastIndexOf() – Last Index of Element

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

lastIndexOf() method searches the searchElement from the end of the array towards the start, and returns the index of the searchElement when there is a match, or returns -1 if the searchElement is not present in the array. if fromIndex is passed as second argument to lastIndexOf(), then the search for the element starts at index fromIndex from the end of the array

Examples

1. find the last index of the element 'cherry' in the array fruits

let fruits = ['apple', 'banana', 'cherry', 'mango', 'banana'];
let searchElement = 'banana';
let lastIndex = fruits.lastIndexOf(searchElement);

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

2. find the last 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', 'banana'];
let searchElement = 'guava';
let lastIndex = fruits.lastIndexOf(searchElement);

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

3. find the last index of the element 'banana' in the array fruits, after a fromIndex of 2

let fruits = ['apple', 'banana', 'cherry', 'mango', 'banana'];
let searchElement = 'banana';
let lastIndex = fruits.lastIndexOf(searchElement, 2);

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


Copyright @2022