JavaScript Array lastIndexOf()

Examples

Find the last index of "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];
let index = fruits.lastIndexOf("Apple");
Try it Yourself »

More than one apple:

const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple");
Try it Yourself »

More examples below.


Description

The lastIndexOf() method returns the last index (position) of a specified value.

The lastIndexOf() method returns -1 if the value is not found.

The lastIndexOf() starts at a specified index and searches from right to left.

By defalt the search starts at the last element and ends at the first.

Negative start values counts from the last element (but still searches from right to left).


Array Find Methods:

MethodFinds
indexOf()The value of the first element with a specified value
lastIndexOf()The index of the last element with a specified value
find()The value of the first element that passes a test
findIndex()The index of the first element that passes a test
findLast()The value of the last element that passes a test
findLastIndex()The index of the last element that passes a test

Syntax

array.lastIndexOf(item, start)

Parameters

Parameter Description
item Required.
The value to search for.
start Optional.
Where to start the search.
Default is the last element (array.length-1).
Negative start values counts from the last element (but still searches from right to left).

Return Value

Type Description
A numberThe position of the specified item.
-1 if the item is not found.


More Examples

Start the search at position 4:

const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", 4);
Try it Yourself »

Start the search at the second last position:

const fruits = ["Orange", "Apple", "Mango", "Apple", "Banana", "Apple"];
let index = fruits.lastIndexOf("Apple", -2);
Try it Yourself »

Browser Support

lastIndexOf() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all modern browsers since July 2013:

Chrome
23
IE/Edge
10
Firefox
21
Safari
6
Opera
15
Sep 2012 Sep 2012 Apr 2013 Jul 2012 Jul 2013


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.