JavaScript Array lastIndexOf()

Posted by

Method

JavaScript Array lastIndexOf() Method

The JavaScript lastIndexOf() method searches the array from the end for the specified item, and returns its position. The lastIndexOf() method returns -1 if the item is not found. This method is similar to the indexOf() method, except it starts searching from the end of the array.

Syntax

The syntax for the lastIndexOf() method is:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

array.lastIndexOf(item, start)

[/dm_code_snippet]

The lastIndexOf() parameters are:

  • item – Required. The item to search for
  • start – Optional. The position in the array to start the search. Default is the last index of the array.

Example

The following example shows how to use the lastIndexOf() method:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var fruits = ["Banana", "Orange", "Apple", "Mango"];
var a = fruits.lastIndexOf("Apple");

// the result of a will be 2

[/dm_code_snippet]

In this example, the lastIndexOf() method searches the array from the end for the item “Apple” and returns its position (2).

Browser Support

The lastIndexOf() method is supported in all major browsers.