JavaScript - Find Index of a Value in Array
Here are some effective methods to find the array index with a value in JavaScript.
Using indexOf() - Most Used
indexOf() returns the first index of a specified value in an array, or -1 if the value is not found.
const a = [10, 20, 30, 40, 50];
// Find index of value 30
const index = a.indexOf(30);
console.log(index);
// Value not found
const notFound = a.indexOf(60);
console.log(notFound);
Output
2 -1
Using findIndex() for Complex Conditions
findIndex() is used for finding the index of an element based on complex conditions. It takes a callback function that can include any logic for locating an item within the array.
const a = [10, 15, 20, 25, 30];
// Find index of first value greater than 18
const index = a.findIndex(value => value > 18);
console.log(index);
Output
2
Using for Loop for Custom Search
Using a for loop gives you complete control over how you search for items. You can stop the loop as soon as you find what you’re looking for, making it a flexible option for setting custom rules.
const a = [5, 10, 15, 20, 25];
let index = -1;
// Find index of value 20
for (let i = 0; i < a.length; i++) {
if (a[i] === 20) {
index = i;
break;
}
}
console.log(index);
Output
3
Using lastIndexOf() for Reverse Search
If you need the last occurrence of a value you can use lastIndexOf() method which returns the index of the last match, or -1 if the value is not found. This is useful what an arrays contain duplicate values.
const a = [5, 10, 15, 10, 5];
// Find last index of value 10
const index = a.lastIndexOf(10);
console.log(index);
Output
3
Importance of Finding Array Indices
Finding array indices is essential for
- Data Manipulation: Helps identify and modify elements based on their position.
- Search Optimization: Enables targeted data retrieval for better performance.
- Conditional Processing: Allows for specific actions on elements that meet criteria.
