Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Kombinera Data och Logik | Sektion
Javascript-Grunder

bookKombinera Data och Logik

Svep för att visa menyn

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.
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 16

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 16
some-alt