Repository navigation
Collection Methods
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.
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
domainto a value in therange.
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)
//=> 6but:
[1, 2, 3].reduce( (total, element) => element * 2 + total, 0)
//=> 12
[1, 2, 3].reduce( (total, element) => element * 2 + total)
//=> 11because of map and reduce inner workings (if there is NOT starting value the first value is given as start but is not processed)
We want to avoid
forEachbecause it is the least-expressive collection-processing method. It communicates the least to other programmers about what we're trying to do. (link)