Skip to main content
eLearner.app
Module 6 · Lesson 1 of 421/32 in the course~10 min
Module lessons (1/4)

map and filter

Two essential methods: they transform an array into a new array, without mutating the original.

map: transform each element

It takes a function, applies it to each element, and returns an array of the same length with the results.

JS
const numeri = [1, 2, 3, 4];

const doppi = numeri.map((n) => n * 2);
// [2, 4, 6, 8]

const stringhe = numeri.map((n) => `n=${n}`);
// ['n=1', 'n=2', 'n=3', 'n=4']

The original stays untouched:

JS
numeri; // [1, 2, 3, 4]  ← unchanged

filter: select a subset

It takes a predicate (a function that returns true/false). It keeps only the elements for which the predicate is true.

JS
const numeri = [1, 2, 3, 4, 5, 6];

const pari = numeri.filter((n) => n % 2 === 0);
// [2, 4, 6]

const grandi = numeri.filter((n) => n > 3);
// [4, 5, 6]

Combining the two

Classic pipeline: filter, then transform.

JS
const prezzi = [12, 5, 100, 30, 7];

const grandiDoppi = prezzi.filter((p) => p > 10).map((p) => p * 2);
// [24, 200, 60]

Try it

Exercise#js.m6.l1.e1
Attempts: 0Loading…

Define `vat(prices, rate)`: given an array of numbers and a rate (e.g. 0.22), return an array with the prices increased by VAT. Use map.

Loading editor…
Show hint

prices.map((p) => p * (1 + rate))

Solution available after 3 attempts

Review exercise

Exercise#js.m6.l1.e2
Attempts: 0Loading…

Define `adultNames(people)`: you receive an array of objects { name, age } and return the array of names of people with age >= 18. Use filter + map.

Loading editor…
Show hint

Chain: .filter(...).map((p) => p.name)

Solution available after 3 attempts