Last active
November 14, 2017 22:02
-
-
Save aderaaij/7039634f9a2c71cccd1cbb893eacd5d9 to your computer and use it in GitHub Desktop.
The `.reduce()` function is one which I found difficult to wrap my head around, so I'm going to try and break it down. Unlike the `.map()` function, `.reduce` can be used to return not just an array, but also an object, number, string or whatever else you'd like. Some of the use cases of the reduce function are flattening, ordering and adding/su…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reduce takes in two arguments, a function and an optional starting point. | |
// example 1 | |
[1, 2, 3].reduce((prev, curr, index) => { | |
console.log(prev, curr, index); | |
return prev + curr; | |
}); | |
// An example of a function that takes in any list of numbers as arguments | |
// and returns the total sum through a reduce function | |
function addNumbers() { | |
return Array.from(arguments).reduce((a, b) => a + b); | |
} | |
const total = addNumbers(55, 399, 392, 18, 44, 98, 76, 29); | |
console.log(total); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment