ప్రధాన కంటెంట్‌కు వెళ్లండి
eLearner.app
మాడ్యూల్ 6 · 4లో పాఠం 1కోర్సులో 21/32~10 min
మాడ్యూల్ పాఠాలు (1/4)

మ్యాప్ మరియు ఫిల్టర్

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

వ్యాయామం#js.m6.l1.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

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.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

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

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది

Review exercise

వ్యాయామం#js.m6.l1.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...

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.

ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు

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

3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది