Skip to content

Collection Methods

sergio edited this page Nov 11, 2020 · 6 revisions

MDN list

Process a collection by visiting each element and do "work" (function()) on it in order to return a new collection or an aggregate value.

map methods return a new Array. reduce methods return a value.

Map (transformer)

we're going to produce a new Array after "transforming" or applying "work" to each element. "Map" comes from mathematics where it means:

  • Taking an independent variable
  • Plugging it into an equation
  • Getting a result back

Mathematicians would say you're mapping a value in the domain to a value in the range.

Reduce (aggregator)

we start with an initial value that we'll call the "memo" or "aggregator." Then we do some "work" involving the element and the "aggregator" and that work updates the "aggregator".

careful because:

[1, 2, 3].reduce( (total, element) => element + total, 0)
//=> 6
[1, 2, 3].reduce( (total, element) => element + total)
//=> 6

but:

[1, 2, 3].reduce( (total, element) => element * 2 + total, 0)
//=> 12
[1, 2, 3].reduce( (total, element) => element * 2 + total)
//=> 11

because of map and reduce inner workings (if there is NOT starting value the first value is given as start but is not processed)

.forEach

We want to avoid forEach because it is the least-expressive collection-processing method. It communicates the least to other programmers about what we're trying to do. (link)

Clone this wiki locally