map, filter, and reject transform lists into something else. map will take an array and transform that into an array of the same length but with each individual transformed.
filter and reject return new arrays based on whether each element of the array passes the passed in callback function.
and find behaves just like filter only it returns the first element.
There are lots of array transformations like this on the array object, but what should you do if you can’t find one that fits? That’s where reduce comes in.
map, filter, reject, and find are all list transformations. They are all pretty specific. But reduce is not. reduce is the multitool of list transformations.
The reduce()
method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Here is another example.
And yet another example.
This one takes a file of tab delimited characters, and transforms them into JS literals.
It does this by:
* splitting on newlines
* mapping the lines into an array of arrays by splitting on tabs
* and then reducing
reduce takes two arguments. A function and a starting object. Because we are reducing to an object literal, here we start with an empty object literal.
The function that wants to reduce takes two arguments.
The first is the object was are constructing customer
. For the first loop this will be our empty object literal {}
. The second object is the thing we are iterating.
So reduce is going to receive this:
['mark johansson', 'waffle', 'iron', '80', '20']
If we ran this now we would get output undefind
. And that is because our var output will be set to what reduce returns on it's final iteration. So lets return the
customer
object.
If we ran this now we would still get an empty object, because we haven’t reduce anything yet.
So let’s rename customer
to be customers
because we are accumulating customers
and for every customer we are going to make customer with their name.
OK. There is a lot going on here. So let’s unpack this. What we are shooting for is this.
And we have the beginning of that here. This line
accumulates, or adds, a new array element every time with a key
of line[0]</code which is the persons names, followed by it's
value
. In this case an empty []
. That's what gives us this.
Now all we have to do is build that inner array.
And we can do that, by pushing
our remaining inner array values.
There is one other gotcha. Because we want to keep reusing the existing customer line each time, and not override it, we modify this line here.
And to better print out our JSON with 2 spaces we modify this line here.
Second video.
Leave a Reply