The lastIndexOf() method works almost exactly like indexOf(), but with one major difference: it searches the array from right to left (starting from the end and moving toward the beginning). It returns the last index at which a given element can be found.
1. Basic Syntax
array.lastIndexOf(searchElement, fromIndex)
- searchElement: The item you want to find.
- fromIndex (Optional): The index at which to start searching backwards. Defaults to array.length – 1.
2. Basic Example
If an element appears multiple times, lastIndexOf() will give you the one closest to the end.
const numbers = [2, 5, 9, 2];
console.log(numbers.lastIndexOf(2));
// Output: 3 (The '2' at the end)
console.log(numbers.indexOf(2));
// Output: 0 (The '2' at the start)
console.log(numbers.lastIndexOf(7));
// Output: -1 (Not found)
3. Using fromIndex
When you provide a fromIndex, the search starts at that position and moves backwards toward index 0.
const fruits = ['Orange', 'Apple', 'Mango', 'Apple', 'Banana'];
console.log(fruits.lastIndexOf('Apple', 2));
// Output: 1
// Search starts at 'Mango' (index 2) and looks left.
// It finds the 'Apple' at index 1.
4. Common Use Case: Checking for Uniqueness
You can determine if a value is the only occurrence in an array by checking if its first index and last index are the same.
const items = ['apple', 'banana', 'cherry'];
function isUnique(arr, item) {
return arr.indexOf(item) === arr.lastIndexOf(item);
}
console.log(isUnique(items, 'apple')); // true
