lastIndexOf Method (Array) (JavaScript)

Returns the index of the last occurrence of a specified value in an array.

array1.lastIndexOf(searchElement[, fromIndex])




Required. The array object to search.


Required. The value to locate in array1.


Optional. The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.

The index of the last occurrence of searchElement in the array, or -1 if searchElement is not found.

The lastIndexOf method searches an array for a specified value. The method returns the index of the first occurrence, or -1 if the specified value is not found.

The search occurs in descending index order. To search in ascending order, use the indexOf Method (Array) (JavaScript).

The array elements are compared to the searchElement value by strict equality, similar to the comparison made by the === operator. For more information, see Comparison Operators (JavaScript).

The optional fromIndex argument specifies the array index at which to begin the search. If fromIndex is greater than or equal to the array length, the whole array is searched. If fromIndex is negative, the search starts at the array length plus fromIndex. If the computed index is less than 0, -1 is returned.

The following examples illustrate the use of the lastIndexOf method.

// Create an array.
var ar = ["ab", "cd", "ef", "ab", "cd"];

// Determine the first location, in descending order, of "cd".
// Output: 4

// Find "cd" in descending order, starting at index 2.
// Output: 1
alert(ar.lastIndexOf("cd", 2));

// Search for "gh" (which is not found).
// Output: -1

// Find "ab" with a fromIndex argument of -3.
// The search in descending order starts at index 3,
// which is the array length minus 2.
// Output: 0
alert(ar.lastIndexOf("ab", -3));

Supported in the Internet Explorer 9 standards document mode. See Version Information.

Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards.

Community Additions