Approach 4 Using Array.indexOf()
To search an element in an array using `Array.indexOf()`, provide the element to search for as an argument. It returns the index of the first occurrence of the element, or -1 if not found.
Example: In this example we searches for the element “3” within the array using Array.indexOf(), returning its index. Output: 2 (indexing starts from 0).
let array = [1, 2, 3, 4, 5];
let searchElement = 3;
let index = array.indexOf(searchElement);
// Returns index 2 (indexing starts from 0)
console.log(index);
Output
2
JavaScript Program to Search an Element in an Array
A JavaScript program searches an element in an array by iterating through each item and comparing it with the target value. If found, it returns the index; otherwise, it returns -1, indicating absence.
Following are the ways to search for an element in an array:
Table of Content
- Using Recursive Approach
- Using Array.reduce() method
- Using a for loop:
- Using Array.indexOf():
- Using includes