Definition and Usage
The findIndex() function for arrays returns the index of the first element that satisfies the condition defined by a callback function.
If no element matches the condition, it returns -1.
In arrays, indexes start at 0.
[π, π, π, π, π΅].findIndex(function(item) {
return item === fruit;
});
// π 2
// In this array, among the elements that meet the condition of being a fruit (π, π),
// the index of the first matching fruit (π) is returned (2).
The findIndex() function is useful for getting the index of the first element in an array that satisfies a specific condition.
Features
- The condition is specified inside a callback function.
- Write the callback so it returnstrueif the condition is met, andfalseotherwise. - Even if multiple elements match the condition, only the index of the first matching element is returned.
- With this behavior, the original array remains unchanged.
Basic Example
The following example demonstrates how to use the findIndex() function to locate the index of the first element in an array that satisfies a given condition. Each step is explained with comments.
// Create an array
const numbers = [1, 3, 7, 4, 6, 8];
// Find the index of the first element that satisfies the condition (even number)
const firstEvenIndex = numbers.findIndex(function(num) {
return num % 2 === 0; // check if the number is even
});
// Output the result
// The first element that satisfies the condition (even number) is 4,
// and its index is 3
console.log(firstEvenIndex); // Output: 3
Syntax
arr.findIndex(callbackFn[, thisArg])
arr is the array to which the findIndex() function is applied.
Parameters
callbackFn |
A callback function that processes each element in the array.
The callback function is executed once for each element, and within it, the condition is defined using a return statement.
If the condition evaluates to true, the element is considered a match.
The findIndex() function then stops iterating and returns the index of the first matching element, ending the execution.
Callback function parameters: callbackFn(element[, index[, array]])
|
|---|---|
thisArg |
Optional. A value to use as this when executing callbackFn. |
The first parameter, the callback function (callbackFn), can take various forms as follows:
// Arrow function
findIndex((element) => { /* β¦ */ })
findIndex((element[, index]) => { /* β¦ */ })
findIndex((element[, index[, array]]) => { /* β¦ */ })
// Callback function reference
findIndex(callbackFn)
findIndex(callbackFn[, thisArg])
// Inline callback function
findIndex(function (element) { /* β¦ */ })
findIndex(function (element[, index]) { /* β¦ */ })
findIndex(function (element[, index[, array]]) { /* β¦ */ })
findIndex(function (element[, index[, array]]) { /* β¦ */ }[, thisArg])
Return value
The index of the first array element that satisfies the condition specified by the callback function.
If no element satisfies the condition, -1 is returned.
How the Callback Function Works
callbackFn(element[, index[, array]])
The findIndex() function iterates through the elements of an array using a callback function defined by the developer. It evaluates each element against the condition provided in the callback.
Inside the callback function, the condition is defined using a return statement. If the condition evaluates to true, the element is considered a match. The findIndex() function then stops iterating and returns the index of the first matching element, ending the execution.
findIndex()
/**
* Callback function
*
* @param {*} element Each element in the array
* @param {number} index Optional. The index of the element
* @param {Array} array Optional. The original array
* @return {boolean} Returns true if the condition is met, otherwise false
*
* The callback function can be a named function (user-defined) or an anonymous function.
* All callback functions can also be written as arrow functions.
*/
/* Using a named function as the callback */
function callbackFn(element[, index[, array]]) { // Named function definition
// Define the condition using a return statement.
}
arr.findIndex(callbackFn); // Pass the defined named function directly as the argument
/* Using an anonymous function as the callback */
arr.findIndex(function (element[, index[, array]]) {
// Define the condition using a return statement
});
Practical Examples
The findIndex() function is used to locate the index of the first element in an array that satisfies a given condition. It can be applied in various scenarios, and is particularly useful for finding the position of a specific value. Let's go through a few examples.
Checking Whether a Specific Element Exists in an Array
You can use findIndex() to check whether an element that satisfies a
specific condition exists in an array.
// Array of user login history
const loginHistory = [
{ user: "Alice", date: "2025-01-01" },
{ user: "Bob", date: "2025-01-02" },
{ user: "Alice", date: "2025-01-05" },
{ user: "Charlie", date: "2025-01-06" },
{ user: "Alice", date: "2025-01-10" },
{ user: "Bob", date: "2025-01-12" }
];
// Target user
const targetUser = "Alice";
// Find the first login using findIndex()
const firstLoginIndex = loginHistory.findIndex(record => record.user === targetUser);
if (firstLoginIndex !== -1) {
const firstLogin = loginHistory[firstLoginIndex];
console.log(`First login:
- User: ${firstLogin.user}
- Date: ${firstLogin.date}`);
} else {
console.log(`No login records found for ${targetUser}.`);
}
/* Output:
First login:
- User: Alice
- Date: 2025-01-01
*/
The findIndex() function is an effective tool for locating the index of the first matching element in an array, making it useful in many different situations.
Compatibility
| Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
findIndex()
|
48 | 12 | 25 | 8 | 4 |
Specifications
| Specification | |
|---|---|
findIndex()
|
ECMAScript Language Specification #sec-array.prototype.findindex |
See also
- JavaScript Array find() Function β Finding an Element with a Callback
- JavaScript Array indexOf() Function β Find an Elementβs Index
- JavaScript Array forEach() Function
- JavaScript Array filter() Function β Filter Array Elements with a Callback
- JavaScript Array reduce() Function β Reducing an Array to a Single Value