Lessons · TypeScript · map and filter
Build a new array from an old one
map transforms each item; filter keeps some; chain them to do both, without a loop and a push.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Most data work is 'take these, keep the ones that..., turn each into...'. map and filter say that in one readable line.
How to think about it
Which items, and what do I want from each? filter answers the first; map the second. Write them in that order so map runs on fewer items.
Worked example
const words = ["tea", "coffee", "milk"];Input.
words.filter(w => w.length > 3).map(w => w.toUpperCase());["COFFEE", "MILK"]: keep the long ones, then upper-case them.
Your turn
Squares of only the positive numbers.
const squares = nums.(n => n > 0).map(n => n * n);
Solve one with the tests running
The trap
forEach returns undefined. If you want a new array back, it is map.
Practise map and filter on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.