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.
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:
numeri; // [1, 2, 3, 4] ← unchangedfilter: select a subset
It takes a predicate (a function that returns true/false). It keeps only the elements for which the predicate is true.
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.
const prezzi = [12, 5, 100, 30, 7];
const grandiDoppi = prezzi.filter((p) => p > 10).map((p) => p * 2);
// [24, 200, 60]Try it
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.
Show hint
prices.map((p) => p * (1 + rate))
Solution available after 3 attempts
Review exercise
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.
Show hint
Chain: .filter(...).map((p) => p.name)
Solution available after 3 attempts