Definition and Usage
The find() function for arrays returns the first element that satisfies the condition defined by a callback function.
If no element matches the condition, it returns undefined.
[π, π, π, π, π΅].find(function(item) {
return item === fruit;
});
// π π
// In this array, among the elements that meet the condition of being a fruit (π, π),
// the first matching fruit (π) is returned.
The find() function is useful for getting 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 first matching element is returned.
- With this behavior, the original array remains unchanged.
Basic Example
The following example demonstrates how to use the find() function to locate 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 first even number
const firstEven = numbers.find(function(num) {
return num % 2 === 0; // check if the number is even
});
// Output the result
console.log(firstEven); // Output: 4
Syntax
arr.find(callbackFn[, thisArg])
arr is the array to which the find() function is applied.
Parameters
callbackFn |
A callback function that processes each element in the array. The callback function is executed for every element and checks the condition defined within it. The condition should be defined using a return statement. If the condition evaluates to true, the element is considered found. The find() function stops iterating and returns the first element that satisfies the condition. Execution then continues after the find() call.Callback function signature: 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
find((element) => { /* β¦ */ })
find((element[, index]) => { /* β¦ */ })
find((element[, index[, array]]) => { /* β¦ */ })
// Callback function reference
find(callbackFn)
find(callbackFn[, thisArg])
// Inline callback function
find(function (element) { /* β¦ */ })
find(function (element[, index]) { /* β¦ */ })
find(function (element[, index[, array]]) { /* β¦ */ })
find(function (element[, index[, array]]) { /* β¦ */ }[, thisArg])
Return value
The first element in the array that satisfies the condition specified by the callback function.
If no element satisfies the condition, undefined is returned.
How the Callback Function Works
callbackFn(element[, index[, array]])
The find() function uses a callback function written by the developer to search array elements according to the desired condition and returns the first element that satisfies the condition.
The callback function of find() checks the condition defined within it for each element in the array. The condition is specified using a return statement. If it evaluates to true, the element is considered found. The find() function stops iterating once the first matching element is found and returns that element. Execution then continues after the find() call.
find()
/**
* 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.find(callbackFn); // Pass the defined named function directly as the argument
/* Using an anonymous function as the callback */
arr.find(function(element[, index[, array]]) {
// Define the condition using a return statement
});
Practical Examples
The find() function is used to locate the first element in an array that satisfies a specific condition. It can be applied in various scenarios. Let's look at a few examples.
Checking for a Specific Element in an Array
You can use this to check whether an element that meets a condition exists in an array.
const numbers = [1, 2, 3, 4, 5];
const target = 3;
// Find the first element that satisfies the condition
const found = numbers.find(element => element === target);
// Output a message based on the result
if (found !== undefined) {
console.log(`The value (${target}) exists in the array.`);
} else {
console.log(`The value (${target}) does not exist in the array.`);
}
// Output: The value (3) exists in the array.
Searching Based on Object Properties
Useful for finding an object in an array of objects based on a specific property value.
// Create an array of person objects
const people = [
{name: "Alice", age: 30},
{name: "Bob", age: 25},
{name: "Charlie", age: 35}
];
// Define the name to search for
const targetName = "Bob";
// Find the first person object in the array whose name matches targetName
const person = people.find(obj => obj.name === targetName);
// Output the result
console.log(person); // Output: {name: "Bob", age: 25}
Searching with a Custom Condition
You can create a custom condition function to search array elements based on your own criteria.
// Create an array of products
const products = [
{name: "Laptop", price: 1000},
{name: "Phone", price: 500},
{name: "Tablet", price: 300}
];
// Define a callback function for the condition
// Here, the condition is to find a product with a price less than 600
const customCondition = product => product.price < 600;
// Find the first product in the array that satisfies the customCondition
const affordableProduct = products.find(customCondition);
// Output the result
console.log(affordableProduct); // Output: {name: "Phone", price: 500}
Using the find() function allows you to efficiently locate the first element that meets a condition, making it useful in various scenarios.
Specifications
| Specification | |
|---|---|
find()
|
ECMAScript Language Specification #sec-array.prototype.find |
Compatibility
| Method |
Desktop Chrome
|
DesktopDesktop Edge
|
Desktop Firefox
|
Safari
|
Node.js
|
|---|---|---|---|---|---|
find()
|
45 | 12 | 25 | 8 | 4 |