How to use array.lastIndexOf() method In Javascript
In this approach, we will use array.lastIndexOf() method. The JavaScript Array lastIndexOf() Method is used to find the index of the last occurrence of the search element provided as the argument to the function.
Syntax:
array.lastIndexOf(element, start)
Example: In this example, we will use arr.indexOf() method to find the last occurrence of target element
Javascript
// Input array const arr = [1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9]; // Target element const target = 8; // Get first index of element using indexOf method() const outputIndex = arr.lastIndexOf(target); // If not found display output if (outputIndex === -1) console.log(target + " is not present in the given" ); else { console.log( "Last index of " + target + " is at index: " + outputIndex ); } |
Output
Last index of 8 is at index: 11
JavaScript Program to find the Index of Last Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the last occurrence of a number in a sorted array. We have the following methods to get the last occurrence of a given number in the sorted array.