find()

The JavaScript find() method loops over an array, returning the first element which passes a test. This test is set with a provided function, if no matching elements are found, undefined is returned.

Syntax

const result = array.find(function(element, index, array), thisVal);

Parameters:

  • function: A function to run for each element in the array. It takes three arguments:
    • element: The current array element being processed.
    • index (optional): The current array element index position.
    • array (optional): The original array find() was called on.
  • thisVal (optional): A value to use as this when executing the callback function.

Basic usage

The find method is ideal for finding specific items in an array. This example finds the first pizza from a menu under $12:

const pizzaMenu = [
  { name: 'Margherita', price: 10 },
  { name: 'Vegetarian', price: 11 },
  { name: 'Pepperoni', price: 13 },
  { name: 'Spicy meat feast', price: 16 },
];

const affordablePizza = pizzaMenu.find(pizza => pizza.price < 12);
console.log("First affordable pizza:", affordablePizza);
// Output: First affordable pizza: { name: 'Margherita', price: 10 }

This example finds the first pizza from the menu by name:

const pizzaMenu = [
  { name: 'Margherita', price: 10 },
  { name: 'Vegetarian', price: 11 },
  { name: 'Pepperoni', price: 13 },
  { name: 'Spicy meat feast', price: 16 },
];

const vegetarianPizza = pizzaMenu.find(pizza => pizza.name === 'Vegetarian');
console.log("Vegetarian pizza:", vegetarianPizza);
// Output: Pepperoni pizza: { name: 'Vegetarian', price: 11 }

Using the index parameter

The index parameter is also accessible in your function:

const pizzaMenu = [
  { name: 'Margherita', price: 10 },
  { name: 'Vegetarian', price: 11 },
  { name: 'Pepperoni', price: 13 },
  { name: 'Spicy meat feast', price: 16 },
];

let foundIndex = -1;

const vegetarianPizza = pizzaMenu.find((pizza, index) => {
  if (pizza.name === 'Vegetarian') {
    foundIndex = index;
    return true;
  }
  return false;
});

if (vegetarianPizza) {
  console.log(`Pizza named ${vegetarianPizza.name} found at menu position ${foundIndex + 1}`);
} else {
  console.log("Vegetarian pizza not found.");
}
// Output: "Pizza named Vegetarian found at menu position 2"

Using the array parameter

The array parameter can be used when you need to access the original array. This example first uses the reduce() method to calculate the avaerage pizza price, then finds the first pizza which is more expensive than the average:

const pizzaMenu = [
  { name: 'Margherita', price: 10 },
  { name: 'Vegetarian', price: 11 },
  { name: 'Pepperoni', price: 13 },
  { name: 'Spicy meat feast', price: 16 },
];

const averagePrice = pizzaMenu.reduce((sum, pizza) => sum + pizza.price, 0) / pizzaMenu.length; // =12.50

const result = pizzaMenu.find((pizza, _, array) => pizza.price > averagePrice);

console.log(result);
// Output: { name: 'Pepperoni', price: 13 }

Matching objects

The find() method is useful for searching objects. The following example finds the first match where an employee works in the IT department and has over y years experience:

const employees = [
  { name: 'John', age: 29, department: 'IT', experience: 5 },
  { name: 'Mike', age: 36, department: 'IT', experience: 8 },
  { name: 'Sarah', age: 22, department: 'HR', experience: 3 },
  { name: 'Lisa', age: 30, department: 'IT', experience: 4 }
];

const seniorITEmployee = employees.find(employee =>
  employee.department === 'IT' && employee.experience > 5
);
console.log("Senior IT employee:", seniorITEmployee);
// Output: Senior IT employee: { name: 'Mike', age: 36, department: 'IT', experience: 8 }

When to use find() vs. other methods

Use find() when:

  • You need to match the first array value which matches a condition.
  • You want the return value to be the matched element (rather than index position or boolean value).
  • You want the search to end when a match is found.

Consider using other methods when:

  • You need to check if all elements in an array are a match (use every()).
  • You need to filter an array with all matching elements (use filter()).
  • You only need to know if any element matches (use some()).
  • You need the the found element index position (use findIndex()).
  • You're looking for a specific value in an array of primitives (use includes()).

Conclusion

The find() method is a powerful tool for searching arrays when you need to find the first element that matches a specific condition. It's particularly useful when working with arrays of objects and complex search criteria. The method returns the first matching element or undefined if no match is found, making it ideal for scenarios where you need the actual element rather than just its presence or index.