Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Array lastIndexOf() method

JavaScript Array lastIndexOf() method

Array Object Reference JavaScript Array object

Example 1

Find the last index value of "Apple":

const

fruits

=

[

"

Apple

"

,

"

Orange

"

,

"

Apple

"

,

"

Mango

"

]

;

let

index

=

fruits

.

lastIndexOf

(

"

Apple

"

)

;

index Output result:

2

Try it »

Example 2

With multiple "Apple" values, find the last index of "Apple":

const

fruits

=

[

"

Orange

"

,

"

Apple

"

,

"

Mango

"

,

"

Apple

"

,

"

Banana

"

,

"

Apple

"

]

;

let

index

=

fruits

.

lastIndexOf

(

"

Apple

"

)

;

index Output result:

5

Try it »


Definition and Usage

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

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

The lastIndexOf() method starts searching from the 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:

Method Description
indexOf() Find the index of the first element with the specified value
lastIndexOf() Find the index of the last element with the specified value
find() Find the value of the first element that passes the test
findIndex() Find the index of the first element that passes the test
findLast() Find the value of the last element that passes the test
findLastIndex() Find the index of the last element that passes the 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

Parameters 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
Digit The position of the specified value. If the value is not found, -1 is returned.

Search starting from index position 4:

Example

const

fruits

=

[

"Orange"

,

"Apple"

,

"Mango"

,

"Apple"

,

"Banana"

,

"Apple"

]

;

let index

=

fruits.

lastIndexOf

(

"Apple"

,

4

)

;

Search starting from the second-to-last position:

Example

const

fruits

=

[

"Orange"

,

"Apple"

,

"Mango"

,

"Apple"

,

"Banana"

,

"Apple"

]

;

let index

=

fruits.

lastIndexOf

(

"Apple"

,

2

)

;


Array Object Reference JavaScript Array object