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? 😀


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.