JavaScript(JS) array method - lastindexof

www.igift‮c.aedi‬om

The lastIndexOf() method is an array method in JavaScript that returns the last index at which a given element can be found in the array, or -1 if it is not present.

Here's the syntax of the lastIndexOf() method:

array.lastIndexOf(searchElement[, fromIndex]);
  • array is the array that the lastIndexOf() method is called on.
  • searchElement is the element to locate in the array.
  • fromIndex is the index to start the search from. If not specified, the search will start from the end of the array.

The lastIndexOf() method returns the last index at which the specified element is found, or -1 if it is not found.

Here's an example of how to use the lastIndexOf() method:

let array = ['apple', 'banana', 'orange', 'banana'];

console.log(array.lastIndexOf('banana')); // 3
console.log(array.lastIndexOf('grape')); // -1
console.log(array.lastIndexOf('banana', 2)); // 1

In this example, we have an array array containing the elements ['apple', 'banana', 'orange', 'banana']. We use the lastIndexOf() method to get the last index of the element 'banana' in the array. We also search for the element 'grape', which is not present in the array. Finally, we use the lastIndexOf() method to search for the element 'banana' starting from the index 2. The output of this code will be:

3
-1
1

Note that the lastIndexOf() method is case-sensitive, so searching for 'Banana' will not match 'banana'. If you need to perform a case-insensitive search, you can convert the array elements to lowercase or uppercase using the toLowerCase() or toUpperCase() methods, and then perform the search.