Sunday, 30 September 2018

JavaScript: Array: lastIndexOf(): Get last index of the element

‘lastIndexOf()’ return the last index at which a given element can be found in the array, or -1 if it is not present.

Syntax
arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])

fromIndex specifies the index at which to start searching backwards.

lastIndexOf.html
<!DOCTYPE html>

<html>

<head>
    <title>lastIndexOf example</title>
</head>

<body>
    <script type="text/javascript">
        var arr = [2, 3, 5, 7, 2, 3, 2, 5];

        document.write("index of first occurrence of element 2 " + arr.lastIndexOf(2) + "<br />");

        document.write("index of occurrence of element 2 from index 5 " + arr.lastIndexOf(2, 5) + "<br />");

        document.write("index of occurrence of element 2 from index 7 " + arr.lastIndexOf(2, 7) + "<br />");
    </script>
</body>

</html>

Open above page in browser, you can able to see following text.

index of first occurrence of element 2 6
index of occurrence of element 2 from index 5 4
index of occurrence of element 2 from index 7 6



Previous                                                 Next                                                 Home

No comments:

Post a Comment