Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Kombinere Data og Logikk | Seksjon
Javascript-Grunnleggende

bookKombinere Data og Logikk

Sveip for å vise menyen

Combining arrays, objects, and functions allows you to build flexible and powerful solutions to many real-world challenges. Arrays help you store and manage lists of data, while objects let you organize related information together. Functions provide the logic to process, transform, and analyze your data. By integrating these building blocks, you can solve practical problems such as searching, filtering, or transforming collections of complex data like user profiles, product lists, or event records.

12345678910111213141516
// Function to filter users by age and return only those who are 18 or older function getAdults(users) { return users.filter(function (user) { return user.age >= 18; }); } const users = [ { name: "Alice", age: 17 }, { name: "Bob", age: 22 }, { name: "Carol", age: 19 }, { name: "Dave", age: 15 } ]; const adults = getAdults(users); console.log(JSON.stringify(adults)); // Output: [{"name":"Bob","age":22},{"name":"Carol","age":19}]
copy

Step-by-step explanation ofiltering users by age.

  1. The users array contains several objects, each representing a user with a name and an age property;
  2. The getAdults function takes the users array as its argument;
  3. Inside getAdults, the filter method is used to create a new array by checking each user object;
  4. The filtering function checks if the age property of each user is greater than or equal to 18;
  5. Only users who meet this condition are included in the new array;
  6. The result is stored in the adults variable, which contains only users who are 18 or older;
  7. When you log adults, you see an array with objects for "Bob" and "Carol", because their ages are 22 and 19, meeting the age requirement.
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 16

Spør AI

expand

Spør AI

ChatGPT

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

Seksjon 1. Kapittel 16
some-alt