Javascript - Array lastIndexOf() Method

The lastIndexOf() method searches the array for the specified item, and returns its position.

Description

The lastIndexOf() method searches the array for the specified item, and returns its position.

The search will start at the specified position, or at the end if no start position is specified, and search backwards to the beginning of the array.

Array lastIndexOf() method returns -1 if the item is not found.

If the item is present more than once, the lastIndexOf method returns the position of the last occurrence.

Syntax

array.lastIndexOf(item,start)

Parameter Values

Parameter Require Description
item Required. The item to search for
start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the beginning

Return

A Number, representing the position of the specified item, otherwise -1

Example

Search an array for the item "Database":

Demo

var myArray = ["XML", "Json", "Database", "Mango"];
var a = myArray.lastIndexOf("Database");
console.log(a);/*from   w  ww.  j  av a2 s  . c  om*/

//Search an array for the item "Database":
var myArray = ["XML","Json","Database","Mango","XML","Json","Database","Mango"];
var a = myArray.lastIndexOf("Database");
console.log(a);

//Search an array for the item "Database", starting the search at position 4:

var myArray = ["XML", "Json", "Database", "Mango", "XML", "Json", "Database", "Mango"];
var a = myArray.lastIndexOf("Database", 4);
console.log( a );

//Search an array for the item "Database", starting the search at position -5:

var myArray = ["XML", "Json", "Database", "Mango", "XML", "Json", "Database", "Mango"];
var a = myArray.lastIndexOf("Database", -5);
console.log( a );

Result