Ana içeriğe geç
eLearner.app
Modül 6 · Ders 1 ders 4Kurstaki 21/32~10 min
Modül dersleri (1/4)

harita ve filtre

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

Egzersiz#js.m6.l1.e1
Denemeler: 0Yükleniyor…

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.

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut

Review exercise

Egzersiz#js.m6.l1.e2
Denemeler: 0Yükleniyor…

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.

Düzenleyici yükleniyor…
İpucu göster

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

3 denemeden sonra çözüm mevcut