Array search from the end with lastIndexOf()

In this chapter you will learn:

  1. How to search a Javascript array from the end

Array lastIndexOf()

lastIndexOf syntax:

lastIndexOf(itemToLookFor, optionalIndexToStartWith)

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.

<!DOCTYPE html><!--from j  a va2 s.c  o  m-->
<html>
<head>
    <script type="text/javascript">
        var numbers = [1,2,3,4,5,4,3,2,1]; 
        document.writeln(numbers.lastIndexOf(4)); //5 
        document.writeln(numbers.lastIndexOf(4, 4)); //3 
        
        
        var person = { name: "JavaScript" }; 
        var people = [{ name: "JavaScript" }]; 
        
        var morePeople = [person]; 
        document.writeln(morePeople.indexOf(person)); //0 

       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Array filter() filters array with the given function.
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()