Sum Array of Integer in Javascript with Reduce

Alternative code to sum up list of integer in Javascript.

var totalArray = [1, 3, 5].reduce(function(prev, current) {
    return prev + current;
});
console.log(totalArray); // 9

Code above equivalent with.

var arrayNumber = [1, 3, 5];
var totalArray = 0;
for (var i = 0; i < arrayNumber.length; i++) {
    totalArray += arrayNumber[i];
}
console.log(totalArray); // 9

I don’t know about performance comparison, soo let you test then and quite similar with python reduce, eh? 😀

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

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