map and filter on numbers
map always gives 3 items back for 3 items in. filter gives back anywhere from 0 to 3.
map makes a new array by changing every item with a function you give it, and filter makes a new array keeping only the items your function says yes to; neither changes the original, and they chain together into clear data pipelines.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given const names = ["asha", "ravi"];, make ["Asha", "Ravi"] with map.
Given an array of { title, done } tasks, print the titles of the tasks that are not done.
Make an array of the even numbers from [1, 2, 3, 4, 5, 6], each squared.
Explain it without notes
What is the difference between map and filter?
Why does ["1", "2", "3"].map(parseInt) return [1, NaN, NaN]?
Why should you filter before mapping when you can?
When should you not use map?
Console
(nothing was printed)Expected console output
[ 100, 250, 40 ] [ 50, 125, 20 ]
[ 100, 40 ]
[ '0: ₹100', '1: ₹250', '2: ₹40' ]
[ true, true, false ]
[]