Skip to content
FORGENO ADS GAMESUnlock all $8

JavaScript · Unit 3: Working with data · Lesson 4 of 6

map and filter

map makes a new array by changing every item: [1, 2, 3].map((n) => n * 2) gives [2, 4, 6].

Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.

The idea

map makes a new array by changing every item: [1, 2, 3].map((n) => n * 2) gives [2, 4, 6].

filter makes a new array with only the items that pass a test: [5, 12, 8].filter((n) => n > 6) gives [12, 8].

Neither one changes the original array. You can chain them: first filter, then map.

Worked example

JavaScript

const prices = [5, 12, 8, 20];
const cheap = prices.filter((p) => p < 10);
console.log(cheap);
console.log(prices.filter((p) => p >= 10).map((p) => p / 2));

It prints

[5, 8]
[6, 10]

Key terms

map and filter
map changes every item into a new array; filter keeps only the items that pass a test.

Practise it in Code Academy

It has 4 exercises (predict the output, fill in the blank and write code from a prompt) and takes about 8 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.

Every lesson is free: no ads, no lives and no paywall.