Chuyển đến nội dung chính
eLearner.app
Mô-đun 6 · Bài học 1 trong tổng số 421/32 trong khóa học~10 min
Bài học theo mô-đun (1/4)

bản đồ và bộ lọc

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

tập thể dục#js.m6.l1.e1
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#js.m6.l1.e2
Nỗ lực: 0Đang tải…

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.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

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

Giải pháp khả dụng sau 3 lần thử