JavaScript Array.find() Method Example

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

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

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare