Tech Junkie Blog: JavaScript Array Methods : lastIndexOf() Method

Monday, June 25, 2018

JavaScript Array Methods : lastIndexOf() Method

The lastIndexOf() method searches for last appearance the element in the array that matches the passed in value. In this example we will search for the value 60.50 in the array.  The lastIndexOf() method takes two arguments.  The first argument is the value to search for, the second argument is optional and specifies the index to start the search at.  If the second argument is omitted the search will start at the first element of the array.

    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 69.50, 76.99];

        var searchAtBeginning = oilPrices.lastIndexOf(60.50);

        var searchAtIndex = oilPrices.lastIndexOf(60.50,2);

        console.log("searchAtBeginning: " + searchAtBeginning);
        console.log("searchAtIndex: " + searchAtIndex);
    </script>

Here is the output:









As you can see the first lastIndexOf() method call returns the index of 4 because that's where 60.50 resides.  It was able to find the element because the second argument was omitted therefore the search starts at the end of the array and returns the first index that it finds from the end.  The second lastIndexOf() method call has the value of 1 as the second argument that tells the method start the search at index 2 in the array because that's the new end of the array according to the method.

No comments:

Post a Comment