What I learned on this mini-project.
This can be used to assess each item of an array against a condition, and create a new one for those that pass.
https://gist.github.com/47d6939c07d45a1af98d8585228a01a4
Here, we used a more concise syntax. If the resulting boolean expression returns true
it will 'pass the condition' and be returned in the filtered array.
inventor
takes the role of the current iterand, much likei
in a traditionalfor (var i = 0; i++; i < arr.length)
loop
This is useful when you wish to apply array methods to a node list extracted from a website (in this case wikipedia).
https://gist.github.com/930f59b9e1695b4ec046dfea67b8efe1
Now, you are able to apply, map
, reduce
, sort
etc... to links.
This method takes an array and attempts to whittle it down to single value (or values shown in the next exanple).
https://gist.github.com/dd72374a1b86c5b0508f39bfa28dca4e
It's best to think of the parameters total
and inventor
as an accumulator
and iterand
. The 0
provides a starting point for the total, since if it were ommited, it would use undefined
to add the first iterand to.
Perhaps a more complex use case for reduce is when trying to reduce multiple elements in an array.
The goal was to reduce each element to the number of occurrences in the array.
https://gist.github.com/d65be6809c921e5ef30a15ecd429ffbb
The key in this case, was to use an empty object
as the initial value for the object, and call obj[key]
for each iteration.