How to use array.findIndex() Method In Javascript
In this approach, we will use Array.findIndex() method. The Javascript Array.findIndex() method is used to return the first index of the element in a given array that satisfies the provided testing function (passed in by the user while calling). Otherwise, if no data is found then the value of -1 is returned.
Syntax:
array.findIndex(function(currentValue, index, arr), thisValue)
Example: In this example, we will use arr.findIndex() method with a callback function as shown in the example to get desired output.
// 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
// findIndex() method
const outputIndex = arr.findIndex((e) => e === target);
// If not found display output
if (outputIndex === -1)
console.log(target + " is not present in the given");
else {
console.log(
"First index of " + target + " is: " + outputIndex
);
}
Output
First index of 8 is: 10
JavaScript Program to Find Index of First Occurrence of Target Element in Sorted Array
In this article, we will see the JavaScript program to get the first occurrence of a number in a sorted array. We have the following methods to get the first occurrence of a given number in the sorted array.