mindixx
mindixx

Reference · module 6

Array methods

Everything this module explains, on one page.

map

Turn every item of an array into something else in one line.

  • map runs a function on every item and collects the results: [1, 2, 3].map(n => n * 2) gives [2, 4, 6]. The result always has as many items as the original.
  • The function you pass is a callback: you hand it over, and map calls it for you, once per item. It receives the item first and its index second: (item, index) => ...
  • map does not change the original array. const doubled = prices.map(p => p * 2); leaves prices as it was, so keep the result in a variable to use it.

The mistake you are about to make

prices.map(p => p * 2); console.log(prices);

const doubled = prices.map(p => p * 2); console.log(doubled);

push and pop change the array in place, so map feels the same. map returns a new array: if you do not keep it, the result is lost and prices stays unchanged.

filter and find

Keep the items you need, find one, and ask questions about all of them.

  • filter keeps only the items for which the callback returns true: [3, 8, 1, 9].filter(n => n > 2) gives [3, 8, 9]. The result can be shorter, or even empty.
  • find returns the first item that matches, not an array: users.find(u => u.name === "Bo") gives the object for Bo, or undefined when nobody matches.
  • some asks whether at least one item matches and every asks whether all do. Both return true or false: [1, 5].some(n => n > 4) is true, [1, 5].every(n => n > 4) is false.

The mistake you are about to make

const bo = users.filter(u => u.name === "Bo"); console.log(bo.age);

const bo = users.find(u => u.name === "Bo"); console.log(bo.age);

You want one person, and filter does find them. filter always returns an array, even of one item, so bo.age is undefined. One item is what find is for.

reduce, sort and chains

Fold an array into one value, sort it correctly and chain methods.

  • reduce folds an array into one value. [1, 2, 3].reduce((sum, n) => sum + n, 0) starts with 0 and adds each item to the running sum, giving 6.
  • sort orders an array in place, but by default it compares items as text: [10, 9, 1].sort() gives [1, 10, 9]. For numbers pass a comparison: .sort((a, b) => a - b).
  • Methods that return arrays can be chained: orders.filter(o => o.paid).map(o => o.total) keeps the paid orders, then takes their totals. Read a chain left to right, one step at a time.

The mistake you are about to make

[10, 9, 1].sort()

[10, 9, 1].sort((a, b) => a - b)

sort with no arguments looks like plain ascending order. It compares strings, and "10" comes before "9", as in a dictionary. For numbers pass the comparison yourself.

Back to the map