Kombinera 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}]
Step-by-step explanation ofiltering users by age.
- The
usersarray contains several objects, each representing a user with anameand anageproperty; - The
getAdultsfunction takes theusersarray as its argument; - Inside
getAdults, thefiltermethod is used to create a new array by checking each user object; - The filtering function checks if the
ageproperty of each user is greater than or equal to 18; - Only users who meet this condition are included in the new array;
- The result is stored in the
adultsvariable, which contains only users who are 18 or older; - 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?
Tack för dina kommentarer!
Avsnitt 1. Kapitel 16
Fråga AI
Fråga AI
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