JavaScript findIndex() method is used to get the index of the element in an Array. This method returns the index of the first array element that satisfies the provided test function or else returns -1.
arr.findIndex(callback(element, index, arr),thisArg)
callback executes a function for each array element.
const array1 = [5, 12, 8, 13, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
Note: The findIndex()
method does not execute the function for empty array elements. If no elements in the array satisfy the testing function, the method returns -1.
Example JavaScript findIndex() method
Simple example code finds even number index in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
function isEven(element) {
return element % 2 == 0;
}
let randomArray = [1, 3, 8, 9, 7];
firstEven = randomArray.findIndex(isEven);
console.log(firstEven);
</script>
</body>
</html>
Output:
Use the arrow operator with findIndex() to get an odd number index.
let randomArray = [1, 3, 8, 9, 7];
firstOdd = randomArray.findIndex((element) => element % 2 == 1);
console.log(firstOdd);
Output: 0
findIndex() with Object elements
const team = [
{ name: "John", age: 10 },
{ name: "Mike", age: 15 },
{ name: "Steve", age: 20 },
{ name: "Rimi", age: 34 },
];
function isAdult(member) {
return member.age >= 18;
}
console.log(team.findIndex(isAdult));
Output: 2
Using the arrow function and deconstructing
adultMember = team.findIndex(({ age }) => age >= 18);
console.log(adultMember); // 2
returns -1 if none satisfies the function
infantMember = team.findIndex(({ age }) => age <= 1);
console.log(infantMember); // -1
Find the index of the first even number in an array:
const numbers = [1, 3, 5, 4, 7, 9, 2, 8, 6];
const evenIndex = numbers.findIndex(function(num) {
return num % 2 === 0;
});
console.log(evenIndex); // 3
Do comment if you have any doubts or suggestions on this JS basic method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version