Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Finding Elements in an Array with the find() Method | Advanced Array Methods and Transformations
JavaScript Data Structures

book
Finding Elements in an Array with the find() Method

Let's explore the find() method, including its syntax and applications, with concrete examples to illustrate its functionality.

find()

While the filter() method sifts through an array to uncover all elements meeting a condition, the find() method is tailor-made for a singular mission – discovering and retrieving the first matching element. Here's a closer look at its syntax:

js
array.find((element, index, array) => {
// Callback body
});

Let's unravel the critical characteristics of the find() method:

  • The original array remains unaltered;

  • It navigates through the array, scrutinizing each element;

  • The method halts upon locating the initial match, returning that specific element;

  • Without a matching element, the method returns undefined.

Find a Task by Order

In this example, the 'find()' method retrieves the task by the 'order' key.

const tasks = [
{ order: 1, name: "Buy groceries" },
{ order: 2, name: "Walk the dog" },
{ order: 3, name: "Read a book" },
];

const firstTask = tasks.find((element) => element.order === 1);
console.log("First task:", firstTask.name); // Output: First task: Buy groceries

const secondTask = tasks.find((element) => element.order === 2);
console.log("Second task:", secondTask.name); // Output: Second task: Walk the dog
1234567891011
const tasks = [ { order: 1, name: "Buy groceries" }, { order: 2, name: "Walk the dog" }, { order: 3, name: "Read a book" }, ]; const firstTask = tasks.find((element) => element.order === 1); console.log("First task:", firstTask.name); // Output: First task: Buy groceries const secondTask = tasks.find((element) => element.order === 2); console.log("Second task:", secondTask.name); // Output: Second task: Walk the dog
copy

1. What is the primary purpose of the find() method?

2. What is a key characteristic of the find() method?

3. What will be the output in the given example below?

question mark

What is the primary purpose of the find() method?

Select the correct answer

question mark

What is a key characteristic of the find() method?

Select the correct answer

question mark

What will be the output in the given example below?

const people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 },
{ name: "David", age: 35 },
];

const personOver30 = people.find((person) => person.age > 30);

console.log(personOver30);

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 5. Kapittel 5

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt