Start learning free

LESSON 266 OF 671 · DESTRUCTURING, SORTING & BUILT-INS

Map and Filter in JavaScript

Lesson

TL ; DR:

The map method builds a new array with every item changed. The filter method builds a new array with only the items that pass a test.


let nums = [1, 2, 3, 4];

let squares = nums.map(n => n * n);                    // [1, 4, 9, 16]

let evens = nums.filter(n => n % 2 == 0);              // [2, 4]

let big = nums.filter(n => n > 2).map(n => n * 10);    // [30, 40]


Full lesson:

You often build a new array from an old one. You already know how to do it with a loop:

let squares = [];

for (let n of nums) {
    squares.push(n * n);
}

The map method does the same in one line. You give it a small function, as you gave one to sort in Custom Sorting. It calls the function on every item and collects the results in a new array.

let squares = nums.map(n => n * n);

Read n => n * n as: take n, give back n * n.

filter takes a function that gives true or false. It keeps only the items that get true.

let evens = nums.filter(n => n % 2 == 0);

You can chain the two. First filter picks the items, then map changes them.

let big = nums.filter(n => n > 2).map(n => n * 10);    // [30, 40]

Both return a new array. The old array, nums, stays as it was.

Watch out: an arrow function with curly braces needs a return. Without one, n => { n * 2 } gives undefined for every item.


Your task

A theater keeps the price of one ticket for each show in prices. Build doubled with map: the price of two tickets for each show.

A quiz keeps its scores in scores. A score of 50 or more passes. Build passed with filter: only the passing scores.

The code already prints both arrays, one value per line.

Expected output:

Two tickets cost 24
Two tickets cost 16
Two tickets cost 30
72 passed
50 passed
90 passed
STEP 1 OF 2
    Ctrl + Enter to check