JavaScript Array findIndex() function is used to return an index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method doesn’t modify the original array.
Syntax
array.findIndex(function(currentValue, index, arr), thisValue)
Parameters
- function(required): It will run for every item in an array.
- currentValue(required): It is the value of the current item.
- index(optional): The index of the current element being processed in the array.
- arr(optional): It is the current array object.
- thisValue(optional): The value is to be passed to a function to be used as its “this” value.
Return value
The index of the first element in the array that passes the test. Otherwise -1.
Visual Representation
Example 1: How to use an Array findIndex() method
let ages = [3, 10, 18, 20, 7];
console.log(ages.findIndex(age => age > 10));
Output
2
The first number that is greater than 10 in the array is 18, which is located at index 2; therefore, the output is 2.
Example 2: Passing predicate
let arr = [11, 21, 19, 29, 17, 23, 31];
index = arr.findIndex((v) => {
return v % 2 === 0;
});
console.log(index)
Output
-1
There are no even numbers in this array, so it returns -1.
Example 3: Where the condition is satisfied with an element
let arr = [11, 21, 19, 20, 17, 24, 31];
index = arr.findIndex((v) => {
return v % 2 === 0;
});
console.log(index)
Output
3
The first even number in the array is 20, which is located at index 3; therefore, the output is 3.
Example 4: Using sparse array
let data = [1, , 3].findIndex((d) => d === undefined)
console.log(data);
Output
1
Example 5: Passing non-array objects
let obj = {name: 'Krunal', age: 30};
let index = obj.findIndex(item => item === 'Krunal');
Output
TypeError: obj.findIndex is not a function
The findIndex() method is specifically useful when more complex searching criteria are needed. It provides more flexibility than methods like indexOf() since it can handle a callback function.
Browser compatibility
- Google Chrome 45
- Edge 12
- Firefox 25
- Safari version 8
- Opera version 32
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.