Javascript Reference - JavaScript Array lastIndexOf() Method








lastIndexOf() starts from the back of the array to do the search.

lastIndexOf() returns the position of the item in the array or -1 if the item isn't in the array.

An identity comparison is used during comparing.

To search from start to end, use the indexOf() method

Browser Support

lastIndexOf() Yes 9.0 Yes Yes Yes

Syntax

lastIndexOf syntax:

lastIndexOf(itemToLookFor, optionalIndexToStartWith)





Parameter Values

Parameter Description
itemToLookFor Required. The item to search
optionalIndexToStartWith Optional. Where to start the search. Negative values starts at the position from the end, and search to the beginning

Return Value

lastIndexOf() returns a number representing the position of the found item, if not found returns -1.

Example


var numbers = [1,2,3,4,5,4,3,2,1]; 
console.log(numbers.lastIndexOf(4)); //5 
console.log(numbers.lastIndexOf(4, 4)); //3 
//from  w w  w.  j  a  v a 2  s .  c om

var person = { name: "JavaScript" }; 
var people = [{ name: "JavaScript" }]; 

var morePeople = [person]; 
console.log(morePeople.indexOf(person)); //0 

The code above generates the following result.





Example 2

The following code shows how to search from then end to the start.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">search</button>
<!--  w ww  .j a  v  a  2 s . c  om-->
<p id="demo"></p>

<script>
function myFunction() {
    var array1 = ["B", "A", "C", "M", "B", "A", "C", "M"];
    var a = array1.lastIndexOf("C", -1);
    var x = document.getElementById("demo");
    x.innerHTML = a;
}
</script>
</body>
</html>

The code above is rendered as follows: