Kodeclik Logo

Our Programs

Learn More

Schedule

Kodeclik Blog

Javascript’s Array find()

The JavaScript Array.find() method is used to search an array and return the first element that satisfies a given condition. It takes a callback function as an argument, which is executed for each element in the array until a match is found.

Example 1: Finding a User by ID

Consider the below code:

const users = [
  { id: 1, name: "Alice", age: 30 },
  { id: 2, name: "Bob", age: 25 },
  { id: 3, name: "Charlie", age: 35 }
];

function findUserById(id) {
  return users.find(user => user.id === id);
}

console.log(findUserById(2)); // 

The output of this will be

{ id: 2, name: "Bob", age: 25 }

This example demonstrates how to use find() to search for a user in an array of objects based on their ID.

First we define an array of users, each user having three attributes, namely id, name, and age. The findUserById function takes an ID as an argument and uses the find() method to return the first user object whose id property matches the given ID. This is useful in scenarios where you need to retrieve user information from a list, such as displaying user profiles or handling user-specific actions on a webpage. In our example, the user whose entry is returned is Bob (with id of 2).

Example 2: Finding the First Available Product

Here is a second example from an e-commerce site of trying to find a product that is in stock:

const products = [
  { name: "Laptop", inStock: false },
  { name: "Smartphone", inStock: true },
  { name: "Tablet", inStock: true }
];

const availableProduct = products.find(product => product.inStock);
console.log(availableProduct); 
// { name: "Smartphone", inStock: true }

In this example, as before, we use the find() method to locate the first product that is in stock. The callback function checks the inStock property of each product object. This could be useful in an e-commerce website where you want to display the first available product to the user or determine if any products are currently in stock.

Example 3: Finding the First Element Meeting a Complex Condition

const temperatures = [18, 22, 25, 29, 32, 35, 28];

function findFirstHotDay(temps) {
  return temps.find((temp, index) => temp > 30 && index > 2);
}

console.log(findFirstHotDay(temperatures)); // 32

In the above example, we consider how to use find() with a more complex condition. The findFirstHotDay function searches for the first temperature above 30°C (86°F) that occurs after the third day in the week. The callback function uses both the element value and its index in the condition. This could be useful in a weather application where you want to find specific weather patterns or alert users about upcoming hot days, considering factors like the day of the week.

In each of the above examples, the find() method efficiently searches through the array and returns the first element that matches the specified condition, making it a powerful tool for retrieving specific data from arrays in various web development scenarios.

Array.find() versus Array.filter()

Note also that the Array.find() method is designed to return only the first element that matches the given condition. It's not possible to make find() itself to return all matching entries. However, there are other array methods that can achieve what you're looking for, such as Array.filter().

For instance, let us attempt to find all prime numbers from 1 to 100. Because find() only returns the first matching element we will use Array.filter() to get all prime numbers. Here's how we can do it:

function isPrime(num) {
  if (num <= 1) return false;
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i === 0) return false;
  }
  return true;
}

const numbers = Array.from({ length: 100 }, (_, i) => i + 1);
const primes = numbers.filter(isPrime);

We first define an isPrime function that checks if a number is prime. It returns false for numbers less than or equal to 1, and then checks for divisibility up to the square root of the number for efficiency. We create an array of numbers from 1 to 100 using Array.from(). The second argument is a mapping function that takes the index i and adds 1 to it, giving us the desired range.

We next use Array.filter() instead of Array.find() to get all prime numbers. The filter() method creates a new array with all elements that pass the test implemented by the isPrime function. Finally, we log the array of prime numbers to the console.

This approach is more efficient than checking every number up to the target number itself. By using Math.sqrt(num) as the upper limit in the isPrime function, we significantly reduce the number of iterations needed to determine if a number is prime.

If you specifically want to use Array.find(), you could use it to find individual prime numbers, like this:

const firstPrimeOver50 = numbers.find(num => num > 50 &
    & isPrime(num));
console.log(firstPrimeOver50); // 53

This would find the first prime number in the array that's greater than 50.

To summarize, while Array.find() is useful for finding a single element that meets a condition, Array.filter() is more appropriate when you need to find all elements that satisfy a condition, as in the case of finding all prime numbers in a range.

Example 4: Using map() and find() together

Even though find() only finds the first element, there are many situations it is useful. Consider the below code:

const users = [
  { id: 1, name: "Alice", age: 30, role: "admin" },
  { id: 2, name: "Bob", age: 25, role: "user" },
  { id: 3, name: "Charlie", age: 35, role: "user" },
  { id: 4, name: "David", age: 28, role: "moderator" }
];

// Find the admin user
const admin = users.find(user => user.role === "admin");

// Map all users to a new array with modified properties
const modifiedUsers = users.map(user => {
  return {
    ...user,
    isAdmin: user.id === admin.id,
    ageNextYear: user.age + 1
  };
});

console.log(modifiedUsers);

In this example, we first use find() to locate the admin user in the array. We then use map() to create a new array of modified user objects. For each user, we spread the existing user properties, add an isAdmin property that's true if the user's id matches the admin's id and also add an ageNextYear property that increments the user's age by 1.

The resulting modifiedUsers array will contain objects like this:

[
  {
    id: 1,
    name: "Alice",
    age: 30,
    role: "admin",
    isAdmin: true,
    ageNextYear: 31
  },
  {
    id: 2,
    name: "Bob",
    age: 25,
    role: "user",
    isAdmin: false,
    ageNextYear: 26
  },
  {
    id: 3,
    name: "Charlie",
    age: 35,
    role: "user",
    isAdmin: false,
    ageNextYear: 36
  },
  {
    id: 4,
    name: "David",
    age: 28,
    role: "moderator",
    isAdmin: false,
    ageNextYear: 29
  }
]

This example demonstrates how find() can be used to locate a specific element in an array, and then that information can be used within a map() operation to transform the entire array based on the found element.

Here are more examples of find() with string applications!

Example 5: Finding the first name that starts with a specific letter

Javascript array find()

This example finds the first name in the array that starts with the letter 'C'.

const names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve'];
const firstNameStartingWithC = 
        names.find(name => name.startsWith('C'));
console.log(firstNameStartingWithC); // Output: Charlie

Example 6: Finding the first email address from a specific domain

This example finds the first email address that ends with '@gmail.com'.

const emails = ['user1@gmail.com', 'user2@yahoo.com', 
     'user3@gmail.com', 'user4@hotmail.com'];
const firstGmailAddress = 
         emails.find(email => email.endsWith('@gmail.com'));
console.log(firstGmailAddress); // Output: user1@gmail.com

Example 7: Finding the first string containing a specific substring

This example finds the first phrase that includes the word ‘Kodeclik’.

const phrases = ['Hello world', 'Good morning', 
     'Kodeclik is fun', 'Coding is great'];
const myPhrase = 
    phrases.find(phrase => phrase.includes('Kodeclik'));
console.log(myPhrase); // Output: Kodeclik is fun

Example 8: Finding the first palindrome in an array of strings

const words = ['level', 'hello', 'radar', 'world', 'deified'];
const firstPalindrome = 
  words.find(word => word === word.split('').reverse().join(''));
console.log(firstPalindrome); // Output: level

This example finds the first palindrome (a word that reads the same backwards as forwards) in the array.

If you liked this blogpost, earn Javascript’s Array.reduce() method and how to find all combinations of array values in Javascript!

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.