How to use array.indexOf() Method In Javascript
In this approach, we will use array.indexOf() method. The JavaScript Array indexOf() Method is used to find the index of the first occurrence of the search element provided as the argument to the method. This method always compares the search element to the element present in the array using strict equality. Therefore, when the search element is not found then it returns -1 because NaN values are never compared as equal.
Syntax:
array.indexOf(element, start)
Example: In this example, we will use arr.indexOf() method to find the target element.
// Input array
const arr = [1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9];
// Target element
const target = 0;
// Get first index of element using
// indexOf method()
const outputIndex = arr.indexOf(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
0 is not present in the given
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.