Skip to content

Instantly share code, notes, and snippets.

@tclancy
Last active December 24, 2015 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tclancy/6719907 to your computer and use it in GitHub Desktop.
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
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
@Laubeee
Copy link

Laubeee commented Sep 8, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment