Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Wyższe metody tablic: map, filter, reduce

Teraz gdy znasz już podstawowe metody tablic, czas poznać trzy najważniejsze metody wyższego rzędu (higher-order methods). Są one fundamentem funkcyjnego programowania w JavaScript i niezwykle przydatne w pracy z danymi dinozaurów.

map() - transformacja danych

Metoda

map()
tworzy nową tablicę, wykonując funkcję na każdym elemencie oryginalnej tablicy. Nie modyfikuje oryginalnej tablicy.

1const dinosaurs = [
2  { name: "Blue", age: 4, species: "Velociraptor" },
3  { name: "Rex", age: 12, species: "T-Rex" },
4  { name: "Bronto", age: 8, species: "Brachiosaurus" }
5];
6
7// Wyciągnięcie samych imion
8const names = dinosaurs.map(dino => dino.name);
9console.log(names); // ["Blue", "Rex", "Bronto"]
10
11// Transformacja do nowego formatu
12const reports = dinosaurs.map(dino => ({
13  label: dino.name + " (" + dino.species + ")",
14  ageInMonths: dino.age * 12
15}));
16console.log(reports);
17// [{ label: "Blue (Velociraptor)", ageInMonths: 48 }, ...]

filter() - filtrowanie danych

Metoda

filter()
tworzy nową tablicę zawierającą tylko elementy, które spełniają podany warunek (funkcja zwraca
true
).

1const dinosaurs = [
2  { name: "Blue", age: 4, diet: "carnivore", dangerLevel: 8 },
3  { name: "Rex", age: 12, diet: "carnivore", dangerLevel: 10 },
4  { name: "Bronto", age: 8, diet: "herbivore", dangerLevel: 2 },
5  { name: "Triki", age: 6, diet: "herbivore", dangerLevel: 3 }
6];
7
8// Filtrowanie drapieżników
9const carnivores = dinosaurs.filter(dino => dino.diet === "carnivore");
10console.log(carnivores.length); // 2
11
12// Dinozaury o wysokim poziomie zagrożenia
13const dangerous = dinosaurs.filter(dino => dino.dangerLevel >= 8);
14console.log(dangerous.map(d => d.name)); // ["Blue", "Rex"]

reduce() - agregacja danych

Metoda

reduce()
redukuje tablicę do pojedynczej wartości, przetwarzając elementy kolejno z akumulatorem.

1const dinosaurs = [
2  { name: "Blue", age: 4 },
3  { name: "Rex", age: 12 },
4  { name: "Bronto", age: 8 },
5  { name: "Triki", age: 6 }
6];
7
8// Suma wszystkich wieków
9const totalAge = dinosaurs.reduce((sum, dino) => sum + dino.age, 0);
10console.log(totalAge); // 30
11
12// Średni wiek
13const avgAge = totalAge / dinosaurs.length;
14console.log(avgAge); // 7.5
15
16// Grupowanie dinozaurów po diecie
17const grouped = dinosaurs.reduce((groups, dino) => {
18  const key = dino.diet || "unknown";
19  if (!groups[key]) groups[key] = [];
20  groups[key].push(dino.name);
21  return groups;
22}, {});

Łączenie metod w pipeline

Prawdziwa moc tych metod ujawnia się, gdy łączymy je w łańcuchy (chaining):

1const dinosaurs = [
2  { name: "Blue", age: 4, diet: "carnivore", dangerLevel: 8 },
3  { name: "Rex", age: 12, diet: "carnivore", dangerLevel: 10 },
4  { name: "Bronto", age: 8, diet: "herbivore", dangerLevel: 2 },
5  { name: "Triki", age: 6, diet: "herbivore", dangerLevel: 3 }
6];
7
8// Pipeline: filtruj drapieżniki -> wyciągnij imiona -> posortuj
9const dangerousNames = dinosaurs
10  .filter(dino => dino.diet === "carnivore")
11  .map(dino => dino.name)
12  .sort();
13
14console.log(dangerousNames); // ["Blue", "Rex"]
15
16// Całkowity poziom zagrożenia drapieżników
17const totalDanger = dinosaurs
18  .filter(dino => dino.diet === "carnivore")
19  .reduce((sum, dino) => sum + dino.dangerLevel, 0);
20
21console.log(totalDanger); // 18
Vai a CodeWorlds