IntermediateLesson 7 of 16
Array Methods: map, filter, reduce – JavaScript
Transforming data functionally – everyday JavaScript.
Instead of loops, you usually write data processing as a chain of filter (select), map (transform) and reduce (summarize). All three return new values and leave the original untouched.
const nutzer = [
{ name: "Ada", alter: 36 },
{ name: "Bob", alter: 17 },
{ name: "Cleo", alter: 29 }
];
const erwachsene = nutzer.filter(n => n.alter >= 18);
const namen = erwachsene.map(n => n.name);
const gesamt = nutzer.reduce((summe, n) => summe + n.alter, 0);
console.log(namen, gesamt); // ['Ada', 'Cleo'] 82For searching and checking there are special methods that stop early:
console.log(nutzer.find(n => n.alter < 18)?.name); // Bob
console.log(nutzer.findIndex(n => n.name === "Cleo")); // 2
console.log(nutzer.some(n => n.alter > 35), nutzer.every(n => n.alter >= 18)); // true false
console.log([1, 2, 3].includes(2), [1, 2, 3].indexOf(5)); // true -1Sorting is a classic trap: sort() without a compare function sorts as text and modifies the array itself.
console.log([10, 9, 1, 100].sort()); // [1, 10, 100, 9]
console.log([10, 9, 1, 100].sort((a, b) => a - b)); // [1, 9, 10, 100]
const sortiert = [...nutzer].sort((a, b) => a.name.localeCompare(b.name));
console.log(sortiert.map(n => n.name));flat flattens nested arrays, flatMap combines map and flat:
console.log([[1, 2], [3, [4]]].flat(), [[1, 2], [3, [4]]].flat(Infinity));
console.log(["a b", "c"].flatMap(s => s.split(" "))); // ['a', 'b', 'c']
console.log(Array.from({ length: 5 }, (_, i) => i * i)); // [0, 1, 4, 9, 16]TipNewer engines offer non-mutating variants:
toSorted(), toReversed(), with() (ES2023) as well as Object.groupBy() (ES2024). Check browser support before using them in production code.