The findIndex() method in JavaScript is used to return the index of the first element in an array that satisfies the provided testing function. If no such element is found, it returns -1. It does not modify the original array.
Syntax
array.findIndex(callback(element, index, array), thisArg);
Parameters
Parameters | Descriptions |
---|---|
callback | A function to test each element of the array. It takes three arguments: |
element | The current element being processed in the array. |
index (Optional) | The index of the current element being processed in the array. |
array (Optional) | The array findIndex() was called upon. |
thisArg (Optional) | A value to use as this when executing the callback function. |
Return Value
Return Type | Description |
---|---|
Number | The index of the first element that satisfies the provided testing function, or -1 if no such element is found. |
Example 1: Finding the Index of an Even Number
This code demonstrates how to use the findIndex() method to find the index of the first even number in an array.
let numbers = [1, 3, 5, 7, 8, 9]; let evenNumberIndex = numbers.findIndex(function(element) { return element % 2 === 0; }); console.log(evenNumberIndex); // Output: 4 (index of number 8)
Example 2: Using Arrow Function
This code uses an arrow function to achieve the same result as the previous example.
let numbers = [1, 3, 5, 7, 8, 9]; let evenNumberIndex = numbers.findIndex(element => element % 2 === 0); console.log(evenNumberIndex); // Output: 4 (index of number 8)
Example 3: Finding the Index of an Object in an Array
This code demonstrates how to use the findIndex() method to find the index of an object in an array based on a specific property value.
let products = [ { id: 1, name: "Product 1" }, { id: 2, name: "Product 2" }, { id: 3, name: "Product 3" } ]; let productIndex = products.findIndex(element => element.id === 2); console.log(productIndex); // Output: 1 (index of product with id 2)
Example 4: Using a Provided thisArg
This code demonstrates how to use the findIndex() method with a provided thisArg to access a variable outside the callback function.
let fruits = ["apple", "banana", "cherry"]; let findByLength = function(element) { return element.length === this.length; }; let fruitIndex = fruits.findIndex(findByLength, { length: 6 }); console.log(fruitIndex); // Output: 1 (index of "banana")
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
45 | 12 | 25 | 32 | 8 |