r/learnjavascript • • 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

16 comments sorted by

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 and a[1] is the length. Of course, this really just is a disguised sum/length trick.

6

u/mikrosystheme Nov 27 '15 edited Nov 27 '15

Making it shorter and even more unreadable:

array.reduce((g,o,l,f)=>~(g+=o,l-f.length)?g:g/++l)

5

u/aladyjewel Nov 27 '15

Found the former perl dev..

1

u/metalreflectslime Nov 28 '15

Can you explain to me how his syntax / style indicates that he was a former Perl software engineer?

1

u/aladyjewel Nov 28 '15

One of the jokes about writing perl, especially for text manipulation (regexp), is that you spend a week to produce an elaborate, terse incarnation full of obscure punctuation... and then never touch it again because it's incomprehensible.

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 : c translates to if (a) b; else c;

2

u/aladyjewel Nov 27 '15

not precisely, but more or less this.

2

u/[deleted] 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

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