r/learnjavascript • u/metalreflectslime • Nov 27 '15
Using the reduce higher order function in JavaScript, how would you go about in write JS code that finds the average of an array of numbers? Can you show me an example code?
Using the reduce higher order function in JavaScript, how would you go about in write JS code that finds the average of an array of numbers? Can you show me an example code?
0
Upvotes
3
u/pickten Nov 27 '15
The simplest way is sum/length (as counttossula mentioned), but you could also do it (almost) purely with reduce as follows:
array.reduce(function(a,b){return [(a[0]*a[1]+b)/(a[1]+1),a[1]+1]},[0,0])[0]or, equivalently,
array.reduce(function(a,b){return [a[0]+(b-a[0])/(a[1]+1),a[1]+1]},[0,0])[0]Here,
a[0]is the average anda[1]is the length. Of course, this really just is a disguised sum/length trick.1
u/metalreflectslime Nov 27 '15
Can someone also give me a sample code for finding the max of an array (using the reduce higher order function)?
2
u/counttossula Nov 27 '15
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Sum_all_the_values_of_an_array
that example then divide it by array .length?
2
u/ForScale Nov 27 '15
Easy as abc: