DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on

Array.find() Method

What is Find Method?

The find() method returns first element in the array that satisfies the provided condition. Otherwise, undefined is returned. It does not modify the original array.

Syntax

Here's the syntax for using find():

const findFirst = arr.find((element, index, array) => {
    // Return true to return the element, false otherwise
});
Enter fullscreen mode Exit fullscreen mode

The callback function is called for each element in the array and takes the following arguments:

  • element: the current element being processed in the array
  • index (optional): the index of the current element
  • array (optional): the array that find() is being applied to

The find() method calls the callback function once for each element in the array, in order, until it finds an element that returns true. If it finds such an element, it returns the value of that element and does not call the callback function for any of the remaining elements. If it does not find an element that returns true, it returns undefined.

Here's an example of how to use find() to find the first even number in an array:

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const firstEven = numbers.find(function (number) {
    return number % 2 === 0;
});

console.log(firstEven); // prints 2
Enter fullscreen mode Exit fullscreen mode

In the example above, the callback function is an anonymous function that takes a single argument, number, and returns true if number is even, and false otherwise. The find() method calls this function for each element in the numbers array and returns the first element that returns true

You can also use an arrow function as the callback function, like this:

const firstEven = numbers.find((number) => number % 2 === 0);

console.log(firstEven); // prints 2
Enter fullscreen mode Exit fullscreen mode

The find() method is useful for finding a single element in an array that satisfies a certain condition.

Examples

Here are a few more examples of how you can use find():

Find the first element that is greater than 10

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

const firstGreaterThan10 = numbers.find((number) => number > 10);

console.log(firstGreaterThan10); // prints 11
Enter fullscreen mode Exit fullscreen mode

Find the first element that is a string

const mixedArray = [1, 2, 3, "a", "b", "c", 4, 5, 6];

const firstString = mixedArray.find((element) => typeof element === "string");

console.log(firstString); // prints 'a'
Enter fullscreen mode Exit fullscreen mode

Find the first element that is an object

const mixedArray = [1, 2, 3, "a", "b", "c", 4, 5, 6, { name: "John" }];

const firstObject = mixedArray.find((element) => typeof element === "object");

console.log(firstObject); // prints { name: 'John' }
Enter fullscreen mode Exit fullscreen mode

Implement the login functionality

Here is an example of how you might use the find() method to implement a login function for an e-commerce website.

Imagine that you have an array of users, and each user is represented by an object with the following properties:

  • id: the unique ID of the user
  • name: the name of the user
  • email: the email address of the user
  • password: the password of the user

You can use the find() method to find the user with the given email address and password, and return the user object if the login is successful, or undefined if the login is unsuccessful.

Here's the code that does this:

let users = [
    { id: 1, name: "Alice", email: "alice@example.com", password: "password1" },
    { id: 2, name: "Bob", email: "bob@example.com", password: "password2" },
    {
        id: 3,
        name: "Charlie",
        email: "charlie@example.com",
        password: "password3",
    },
];

function login(email, password) {
    const user = users.find(
        (user) => user.email === email && user.password === password
    );

    if (user) {
        console.log(`Welcome, ${user.name}!`);
        return user;
    } else {
        console.log("Incorrect email or password");
        return undefined;
    }
}

const loggedInUser = login("alice@example.com", "password1");
// prints 'Welcome, Alice!' and returns the user object

const loggedInUser = login("abc@gmail.com", "password1");
// prints 'Incorrect email or password' and returns undefined
Enter fullscreen mode Exit fullscreen mode

Find product by id

Imagine that you have an array of products, and each product is represented by an object with the following properties:

  • id: the unique ID of the product
  • name: the name of the product
  • price: the price of the product
  • categories: an array of categories that the product belongs to

You can use the find() method to find a product by its ID, and return the product object if it is found, or undefined if it is not found.

Here's the code that does this:

let products = [
    {
        id: 1,
        name: "Product 1",
        price: 10,
        categories: ["Category 1", "Category 2"],
    },
    {
        id: 2,
        name: "Product 2",
        price: 15,
        categories: ["Category 2", "Category 3"],
    },
    {
        id: 3,
        name: "Product 3",
        price: 20,
        categories: ["Category 1", "Category 3"],
    },
];

function getProductById(id) {
    const product = products.find((product) => product.id === id);

    if (product) {
        console.log(`Product found: ${product.name}`);
        return product;
    } else {
        console.log("Product not found");
        return undefined;
    }
}

let product = getProductById(2);
// prints 'Product found: Product 2' and returns the product object

product = getProductById(4);
// prints 'Product not found' and returns undefined
Enter fullscreen mode Exit fullscreen mode

In the example above, the callback function is an anonymous function that takes a single argument, product, and returns true if product.id is equal to the given id, and false otherwise. The find() method calls this function for each element in the products array and returns the first element that returns true. If no element returns true, it returns undefined.

findIndex()

The findIndex() method is similar to the find() method, except that it returns the index of the element that satisfies the condition, instead of the element itself.

Here's an example of how to use findIndex() to find the index of the first even number in an array:

const numbers = [2, 4, 6, 8, 10];

const firstEvenIndex = numbers.findIndex((number) => number % 2 === 0);

console.log(firstEvenIndex); // prints 1

const firstOddIndex = numbers.findIndex((number) => number % 2 === 1);

console.log(firstOddIndex); // prints -1
Enter fullscreen mode Exit fullscreen mode

In the example above, the callback function is an anonymous function that takes a single argument, number, and returns true if number is even, and false otherwise. The findIndex() method calls this function for each element in the numbers array and returns the index of the first element that returns true. If no element returns true, it returns -1.

When to use find()

The find() method is useful when you want to find a single element in an array that satisfies a certain condition. For example, you can use it to find the first element that is greater than 10, or the first element that is a string, or the first element that is an object.

Conclusion

In this article, you learned about the find() and findIndex() methods, which are used to find a single element in an array that satisfies a certain condition. You also learned how to use these methods to implement the login functionality for an e-commerce website, and to find a product by its ID.

Top comments (0)