Turn lists into useful results
Use map, filter and find for catalogues, dashboards and search results.
- Choose map, filter or find for a task
- Read callback functions and array results
- Avoid changing the original list by accident
Real pages handle lists: products in a shop, messages in an inbox, and rows in a report. map transforms every item into a new array. filter keeps all matching items in a new array. find returns the first match or undefined. Each receives a callback function that runs for an item.
1const products = [
2 { name: "Notebook", stock: 4 },
3 { name: "Pen", stock: 0 },
4 { name: "Marker", stock: 2 },
5];
6const available = products.filter((product) => product.stock > 0);
7console.log(available.map((product) => product.name).join(", "));
8console.log(products.length);Notebook, Marker 3
Try it
Up to 15 XPChoose the array method
Match each job to the method that returns the result you need.
“Get every product name”
“Keep all products in stock”
“Get the first product with a matching ID”
These methods do not mutate the original array. map and filter return new arrays. find may return undefined, so check before reading properties. reduce can combine items into one value, but a clear loop is often easier for a beginner to read.
Key takeaways
map transforms; filter keeps all matches; find selects the first match.
A callback describes what happens for each item.
Check a find result before using its properties.
Lesson quiz
2 questions · pass with 2 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write JavaScript
Write the program, run it against the test cases, and use the feedback to build your JavaScript skills.
Make an in-stock list
Input is JSON for a product array with name and stock. Keep products whose stock is above zero, map to their names, sort alphabetically, then print names joined by , . If none are available, print No items in stock.
- Some available
- Nothing available
JavaScript runs in a sandboxed browser frame with a 1.5 second time limit. Input is available as the string variable input.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…