Array reduce Javascript.

Example to show on how to use Array reduce to make a average of an array.

First an example on how to do it with a for loop.


var scores=[20, 34, 55, 46, 77];

var sum=0;
for(var i = 0; i < scores.length; i++) {
sum +=scores[i];
}
sum = sum / scores.length;
console.log(sum);

And now with the reduce function provided by Array prototype, the sintax is:

array.reduce(callback(accumulator, currentval, index, allarray))

var sum = scores.reduce(function(accum, cur, index, array) {
return accum+cur;
});

sum = sum / scores.length;

console.log(sum);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s