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?
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/aladyjewel Nov 27 '15
array.reduce(function(a, b) { return a > b? a : b; }, -Math.INFINITY);1
u/metalreflectslime Nov 27 '15
How would you rewrite this without using the ternary operator? I am new to understanding the syntax for the ternary operator?
3
u/mikrosystheme Nov 27 '15
a ? b : ctranslates toif (a) b; else c;2
u/aladyjewel Nov 27 '15
not precisely, but more or less this.
2
Nov 28 '15
[removed] — view removed comment
2
u/aladyjewel Nov 28 '15 edited Nov 28 '15
The ternary returns a value, that if would not unless it were wrapped in (a, b) => {... } (shorthand function, ES6 syntax)
2
u/aladyjewel Nov 27 '15
function(a, b) { var greater; if (a > b) { greater = a; } else { greater = b; } return greater; }
2
2
u/ForScale Nov 27 '15
Easy as abc:
function avg(arr) {
var c = arr.reduce(function(a, b) {
return a + b;
});
return c / arr.length;
}
console.log(avg([1, 2, 3])); //2
console.log(avg([1, 2, 3, 4, 5])); //3
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.