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 === π;
}) π 1
The findIndex()
function is useful for finding the index of an element in an array that meets a specific condition.
Features
- The condition is specified inside a callback function.
- Write the callback so it returnstrue
if the condition is met, andfalse
otherwise. - 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.
findIndex()
function
/*
* Note:
* In arrays, indexes start at <code>0</code>.
* The first element has an index of <code>0</code>, the second element has an index of <code>1</code>.
*/
// Create an array
const colors = ["red", "green", "blue"];
// Find the index of "green" in the array
const greenIndex = colors.findIndex(function(color) {
return color === "green"; // Check if the array element equals "green"
});
// Output the result
console.log(greenIndex); // Output: 1
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.
Understanding Basic Value Position Lookup
The findIndex()
function can be used to locate the position of a specific value in an array. For example, it can search for a particular number, string, or even an object.
// Finding the position of a specific value
// Locate the position of a value in an array
const numbers = [1, 2, 3, 4, 5];
const target = 3;
// Use findIndex() to find the position of the value
const index = numbers.findIndex(num => num === target);
if (index !== -1) {
console.log(`The position of ${target} is ${index + 1}.`);
} else {
console.log(`The value ${target} was not found.`);
}
// Output: 'The position of 3 is 3.'
Finding the First Document Containing a Keyword
The findIndex()
function can be used to search a list of documents for the first one containing a specific keyword, and then return its position. This is useful when searching for text that matches certain conditions.
// Document list
const documents = [
"JavaScript is a web programming language.",
"You can build servers using Node.js.",
"React is a popular frontend library.",
"Python is a general-purpose programming language."
];
// Keyword to search for
const targetKeyword = "Node.js";
// Use findIndex() to find the first document containing the keyword
const index = documents.findIndex(document => document.includes(targetKeyword));
if (index !== -1) {
console.log(`The first document containing "${targetKeyword}" is at position ${index + 1}.`);
} else {
console.log(`No document containing "${targetKeyword}" was found.`);
}
// Output: 'The first document containing "Node.js" is at position 2'
Code Explanation
The includes()
function for strings checks whether a given string contains a specified substring. If the substring is found, it returns true
; otherwise, it returns false
.
Finding the First Notification for a Specific User
The findIndex()
function can also be used in a real-time notification system to locate the first event that matches a given condition and then deliver the notification to the user. The following example simulates this process.
// Real-time notification events
const notificationEvents = [
{id: 1, message: "New message received", recipient: "Alice"},
{id: 2, message: "Order completed", recipient: "Bob"},
{id: 3, message: "Meeting started", recipient: "Charlie"},
{id: 4, message: "Task reminder", recipient: "Alice"}
];
// Target user
const targetRecipient = "Alice";
// Use findIndex() to find the first notification for the user
const index = notificationEvents.findIndex(event => event.recipient === targetRecipient);
if (index !== -1) {
const firstNotification = notificationEvents[index];
console.log(`The first notification for "${targetRecipient}": ${firstNotification.message}`);
// Here, you could add the logic to actually deliver the notification to the user
} else {
console.log(`No notification found for "${targetRecipient}".`);
}
// Output: 'The first notification for "Alice": New message received'
This code searches the list of real-time notification events for the first one that matches the target user and outputs the message. While the logic for delivering the notification is not included, it could easily be added to make this part of an actual notification system.
// Real-time notification events
const notificationEvents = [
{id: 1, message: "New message received", recipient: "Alice"},
{id: 2, message: "Order completed", recipient: "Bob"},
{id: 3, message: "Meeting started", recipient: "Charlie"},
{id: 4, message: "Task reminder", recipient: "Alice"}
];
// Target user
const targetRecipient = "Alice";
// Use find() to get the first notification for the user
const firstNotification = notificationEvents.find(event => event.recipient === targetRecipient);
if (firstNotification) {
console.log(`The first notification for "${targetRecipient}": ${firstNotification.message}`);
// Here, you could add the logic to actually deliver the notification to the user
} else {
console.log(`No notification found for "${targetRecipient}".`);
}
// Output: 'The first notification for "Alice": New message received'
Code Explanation
In arrays, the find()
function identifies the first element that fulfills the specified condition and returns that element.
When writing code, the choice of function or approach depends on the specific task. JavaScript provides a variety of array methods and tools. While find()
and findIndex()
share similar goals, choosing between them depends on whether you need the element itself or its position.
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.
Browser compatibility
Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
---|---|---|---|---|
findIndex()
|
48 | 12 | 25 | 8 |
Specifications
Specification | |
---|---|
findIndex()
|
ECMAScript Language Specification #sec-array.prototype.findindex |