Lesson 37 - JavaScript Array Method – findIndex()
The findIndex() method is similar to find(), but instead of returning the first matching element, it returns the index of the first element that meets the specified condition. If no elements match, it returns -1.
array.findIndex(callback(element, index, array), thisArg);
callback: A function that runs for each element.element: The current element being processed.index(optional): The index of the current element.array(optional): The array thatfindIndex()was called on.thisArg(optional): The value to use asthisinside the callback function.
Explanation
- It loops through the array and applies a callback function to each element.
- If an element meets the condition, its index is returned immediately.
- If no element matches, it returns
-1.
Example 1: Finding the Index of the First Even Number
let numbers = [3, 7, 10, 15, 20];
let firstEvenIndex = numbers.findIndex(num => num % 2 === 0);
console.log(firstEvenIndex); // Output: 2
- Returns
2, the index of the first even number (10).
Example 2: Finding an Object's Index in an Array
let users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
let index = users.findIndex(person => person.age > 30);
console.log(index); // Output: 2
- Returns
2, the index of{ name: "Charlie", age: 35 }.
Example 3: Searching for a Missing Value
let numbers = [2, 4, 6, 8];
let index = numbers.findIndex(num => num > 10);
console.log(index); // Output: -1
- Returns
-1since no number is greater than10.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson37-findIndex.html.
- Name it
-
Write the Code:
-
Copy the following:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 37 - findIndex() Method</title> </head> <body> <h2>Find the First Number Greater than 50</h2> <p id="result"></p> <script> let numbers = [10, 20, 30, 40, 60, 80]; let index = numbers.findIndex(num => num > 50); document.getElementById("result").textContent = "Index of first number > 50: " + index; </script> </body> </html>
-
-
Save the File.
-
Open it in a Browser to See the First Large Number's Index.
Experiment
- Find the index of the first odd number in an array.
- Get the index of the first product that is out of stock from an inventory list.
- Find the index of the first word in a list that starts with "J".
Key Takeaways
findIndex()returns the index of the first element that matches the condition.- If no match is found, it returns
-1. - Useful for locating positions of elements in an array.