DevPath · Learn to code ESPTEN

Arrays and their methods

Functional methods: map, filter, reduce and more

Functional methods

These methods receive a function and iterate over the array for you. They make the code clearer and more declarative than a manual loop. And another bit of the ⚠️ CLASSIC TRAP: map and filter don't mutate (they return a new array); sort does mutate. Almost all of them return something new, but sort is the exception that can catch you off guard.

forEach: run something for each element

[1, 2, 3].forEach(n => console.log(n)); // prints 1, 2 and 3

map: transform each element

Returns a new array with each element transformed:

const numbers = [1, 2, 3];
const doubles = numbers.map(n => n * 2); // [2, 4, 6]

filter: keep only some

Returns a new array with the elements that meet a condition:

const evens = [1, 2, 3, 4].filter(n => n % 2 === 0); // [2, 4]

reduce: summarize everything into one value

Accumulates the elements into a single result. It receives an accumulator and an initial value:

const total = [1, 2, 3, 4].reduce((acc, n) => acc + n, 0); // 10

find, some and every

[5, 12, 8].find(n => n > 10);    // 12 (the first one that matches)
[1, 2, 3].some(n => n > 2);      // true (at least one matches)
[2, 4, 6].every(n => n % 2 === 0); // true (all match)

sort: ordering

sort orders by modifying the array. For numbers you need a comparison function:

const nums = [3, 1, 2];
nums.sort((a, b) => a - b); // [1, 2, 3] ascending
nums.sort((a, b) => b - a); // [3, 2, 1] descending

Without a comparison function, sort orders as text: [10, 2, 1] would turn into [1, 10, 2]. Watch out!

Chaining methods

Since many return arrays, you can chain them:

const result = [1, 2, 3, 4, 5, 6]
  .filter(n => n % 2 === 0) // [2, 4, 6]
  .map(n => n * 10)         // [20, 40, 60]
  .reduce((a, b) => a + b, 0); // 120

Filter, transform and summarize in a single pipeline: that's how carts, scores or any real list get processed without a single hand-written loop. And this is just the start: soon each element will stop being a lone number and become an object (a product with a price and a name, a user with an email)... and these same methods will shine even brighter.

Examples

map + filter + reduce working together

const prices = [10, 25, 5, 40];
const expensive = prices.filter(p => p >= 25); // [25, 40]
const withTax = expensive.map(p => p * 1.21);  // [30.25, 48.400000000000006]
// ⚠️ Decimals in binary aren't exact: 40 * 1.21 doesn't give a "round" 48.4.
const total = withTax.reduce((a, b) => a + b, 0);
console.log(expensive, withTax, total);

Sorting numbers correctly

const ages = [30, 5, 21, 8];
ages.sort((a, b) => a - b);
console.log(ages); // [5, 8, 21, 30]
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Searching for elementsView the module →