← Zurück zum Kurs: JavaScript from scratch

Array methods: forEach, map, filter, find, reduce and sort

Video folgt in Kürze

Higher-order methods receive a function as an argument and apply it to each element of the array. With them you write less and more expressive code than with a for. Before starting, a key idea: map, filter, find and reduce do not modify the original array, they return a new result. This makes code easier to understand and debug. You will see arrow functions like (x) => x * 2; we will study them in depth in week 5, for now read them as a short way of saying: given x, return x times 2.

forEach and map

forEach runs a function for each element and returns nothing; it is used for effects such as printing data. map transforms each element and returns a new array with the same length. If you need a result, use map; if you only need to do something with each element, forEach. A common mistake is using map and forgetting to save or use the result.

javascript
const prices = [10, 20, 30];

prices.forEach((price, index) => {
  console.log(index, price);
});

const withTax = prices.map((price) => price * 1.21);
console.log(withTax); // [ 12.1, 24.2, 36.3 ] (roughly)
console.log(prices);  // [ 10, 20, 30 ] unchanged

const names = ['ana', 'luis'];
console.log(names.map((n) => n.toUpperCase())); // [ 'ANA', 'LUIS' ]

filter and find

filter returns a new array with only the elements for which the function returns true; if none match, it returns an empty array. find returns the first element that meets the condition, or undefined if there is none. Its relative findIndex returns the position. You also have some (does any element match?) and every (do all match?), which return booleans.

javascript
const ages = [12, 18, 25, 9, 40];

console.log(ages.filter((a) => a >= 18)); // [ 18, 25, 40 ]
console.log(ages.find((a) => a > 20));    // 25
console.log(ages.find((a) => a > 100));   // undefined
console.log(ages.findIndex((a) => a === 9)); // 3
console.log(ages.some((a) => a < 10));    // true
console.log(ages.every((a) => a > 5));    // true

reduce: from a list to a single value

reduce walks through the array accumulating a result. It receives a function with two main parameters, the accumulator and the current element, and an initial value as the second argument. On each turn, what the function returns becomes the new accumulator. With reduce you can add, count, group or build objects. Always give the initial value: without it, the first element is used as the accumulator and an empty array causes an error.

javascript
const cart = [
  { item: 'book', price: 12, qty: 2 },
  { item: 'pen', price: 1.5, qty: 10 },
  { item: 'bag', price: 30, qty: 1 }
];

const total = cart.reduce((acc, line) => acc + line.price * line.qty, 0);
console.log(total); // 69

// Chaining: names of items that cost more than 10 per unit
console.log(cart.filter((l) => l.price > 10).map((l) => l.item)); // [ 'book', 'bag' ]

Sorting with sort

sort orders the array in place, meaning it modifies it. Careful: by default it converts elements to text and sorts them alphabetically, so [10, 9, 1].sort() gives [1, 10, 9]. For numbers pass a comparison function (a, b) => a - b for ascending order or (a, b) => b - a for descending. If you do not want to alter the original, use toSorted, available in Node 20 and modern browsers, which returns a sorted copy.

javascript
const nums = [10, 9, 1, 100];
console.log(nums.toSorted());               // [ 1, 10, 100, 9 ] (text order)
console.log(nums.toSorted((a, b) => a - b)); // [ 1, 9, 10, 100 ]
console.log(nums);                           // original unchanged

const people = [{ n: 'Zoe', age: 30 }, { n: 'Abe', age: 22 }];
console.log(people.toSorted((a, b) => a.age - b.age)[0].n); // Abe

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →