JavaScript Array lastIndexOf()Method

Array 对象参考手册JavaScript Array Object

Example 1

Find the last index of "Apple":

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

indexOutput:

2

Try it Yourself »

Example 2

Multiple "Apple"s, find the last index of "Apple":

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

indexOutput:

5

Try it Yourself »

Definition and Usage

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

If the specified value is not found, the lastIndexOf() method returns -1.

The lastIndexOf() method searches from a specified index position, from right to left (from the specified position to the beginning of the array).

By default, the search starts from the last element of the array and ends at the first element.

A negative start index counts from the last element of the array (but still searches from right to left).

Array search methods:

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

Browser Support

lastIndexOf() is an ECMAScript 5 (ES5) feature.

ES5 (JavaScript 2009) has been fully supported in all modern browsers since July 2013.

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

Syntax

array.lastIndexOf(item, start)

Parameters

Parameter Description
item Required. The value to search for.
start Optional. The position to start the search. Defaults to the last element of the array (array.length - 1). A negative start index counts from the last element of the array (but still searches from right to left).

Return Value

Type Description
Number The position of the specified value. If the value is not found, returns -1.

Start searching from index 4:

Example

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

Start searching from the second-to-last position:

Example

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


Array 对象参考手册JavaScript Array Object

Other Extensions