Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • lastIndexOf() method of JavaScript Array

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 95
    Comment on it

    JavaScript Array lastIndexOf() method : The lastIndexOf() method returns the last index of the given item inside the array. This method is used when array has an element more then once. It returns the numeric value 0 or greater if element found, and return -1 if no element found. Index count starts from 0.


    Syntax of Array lastIndexOf() method :

    array.lastIndexOf(element , start)
    

    element : Required. This is the element need to search in the array and return the position.

    start : Optional. This is the position from where the search starts from backward.


    Example of Array lastIndexOf() method : Here I will show you how to get the last index value of any element exist in array.

    Sample1.html

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>To display last index of the element, click the button "show last index".</p>
    <button onclick="showIndex()">show last index</button>
    <p id="container"></p>
    
    <script>
    function showIndex() {
        var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Rajesh", "Pramod"];
        var result = students.lastIndexOf("Rajesh");
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    

    Output :

    6
    

    In the above example it results the last occurrence of the Rajesh. In the Sample2.html I will show how to search element from given index.


    Sample2.html

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>To display last index of the element from a given position, click the button "show last index".</p>
    <button onclick="showIndex()">show last index</button>
    <p id="container"></p>
    
    <script>
    function showIndex() {
        var students = ["Ashok", "Nitin Kumar", "Rajesh", "Pankaj", "Sumit", "Manish", "Rajesh", "Pramod"];
        var result = students.lastIndexOf("Rajesh", 4);
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    

    Output :

    2
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: