-
-
Save tclancy/6719907 to your computer and use it in GitHub Desktop.
Coffeescript/ JavaScript reduce() initial value confuses me. Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
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
coffee> values = [2, 4, 4, 4, 5, 5, 7, 9] | |
[ 2, | |
4, | |
4, | |
4, | |
5, | |
5, | |
7, | |
9 ] | |
# lack of an initial value doesn't matter here? | |
coffee> avg = values.reduce((sum, x) => sum + parseFloat(x)) / values.length | |
5 | |
coffee> (x-avg)*(x-avg) for x in values | |
[ 9, | |
1, | |
1, | |
1, | |
0, | |
0, | |
4, | |
16 ] | |
coffee> values.reduce (sum, x) => sum + (x-avg)*(x-avg) | |
# WRONG | |
25 | |
# Correct when providing initial default of 0 here (ignore my inconsistency in how I'm squaring here :) | |
coffee> values.reduce(((sum, x) => sum + Math.pow(x - avg, 2)), 0) | |
32 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is because in your first example, in the first loop "sum" equals 2 and x equals 4. 2+4 = 6, same as 0+2+4 (which is calculated if you also give an initial value)
But in your second example you start with sum=2 instead of sum = 0 + pow(2 - avg, 2)
The function is executed arrayLength-1 times, not arrayLength times. I hope this helps.