JavaScript Array.find() Method Example

The JavaScript Array find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

Syntax

arr.find(callback[, thisArg])
  1. callback - Function to execute on each value in the array, taking three arguments:
  • element - The current element being processed in the array.
  • index - Optional. The index of the current element being processed in the array.
  • array - Optional. The array find was called upon.
  1. thisArg - Optional. Object to use as this when executing the callback.

JavaScript Array.find() Method Examples

Example 1: Simple Array.find() Example

var array1 = [15, 20, 25, 30, 35];

var found = array1.find(function(element) {
  return element > 12;
});

console.log(found);
Output:
15

Example 2: Find an object in an array by one of its properties

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function isCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(isCherries));
Output:
{ name: 'cherries', quantity: 5 }

Example 3: Find a prime number in an array

function isPrime(element, index, array) {
  var start = 2;
  while (start <= Math.sqrt(element)) {
    if (element % start++ < 1) {
      return false;
    }
  }
  return element > 1;
}

console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5

Comments