Skip to main content

find

The find() method returns the first element of the array that satisfies the given condition. If no condition is andsatisfied, undefined is returned.

Syntax

// Arrow function
find((element) => {
/* … */
});
find((element, index) => {
/* … */
});
find((element, index, array) => {
/* … */
});

// Callback function
find(callbackFn);

// Inline callback function
find(function (element) {
/* … */
});
find(function (element, index) {
/* … */
});
find(function (element, index, array) {
/* … */
});

The find method execute a callback function for each element of the array until the callback returns a truthy value. If so, find will retun the value, otherwise it will return undefined.

Parameters

  • callBackFn: The function to be executed on each element in the array. The function will have the following arguments:

    • element: The current element of the array.

    • index: The index of the element in the array.

    • array: The array on which find() is called.

Example

find method in array

let array = ["Black", "Yellow", "Blue", "White", "Red", "Blue"];
console.log(array.find((element) => element == "Blue"));
console.log(array);

find method in object

const basket = [
{ name: "apples", quantity: 5 },
{ name: "bananas", quantity: 2 },
{ name: "cherries", quantity: 15 },
{ name: "orange", quantity: 2 },
];

const result = basket.find((element) => element.quantity === 2);

console.log(result); // { name: 'bananas', quantity: 2 }