Various methods for Javascript sum array

1
398
Various methods for Javascript sum array

Talking about Javascript sum array, this is a very basic question for any Javascript beginners. But how many ways do you know to calculate the summation of an Javascript array?

Okay, let us dig out all of possible ways to do it.

ATTENTION!!!

This article is dedicated to new Javascript developers or beginners only. If you are an experienced Javascript developers, you don’t have to read this since it does not go deep into explaining anything at all. Just a simple introduction!

Table of Contents

Javascript Sum Array

Array is, of course, a collection of data put into a variable in Javascript.

This is not the same as other languages where data should be in the same data type, but you can put into a Javascript array any data type.

So, before calculating Javascript sum array, we should make assumption that array should contain only number type value or object element with number properties.


var coll = [1, 2, 3];

var dataset = [
    { 'city': 'New York', 'distance': 1024 },
    { 'city': 'Chicago',  'distance': 2048 },
    { 'city': 'Denver',   'distance': 3000 },
    ...
];

That’s the condition for following methods to work.

Naive element summation

With a very short array and we can directly use plus sign to make sum of all elements. Just like this:


var coll = [1, 2, 3];

var sum = coll[0] + coll[1] + coll[2];

Of course, this is applied only with very short arrays.

In reality, you will rarely use it anyway.

I just want to mention to let you know such a method existed.

Using basic for loop

Have you learned through Javascript loop yet? Alright, let’s try it.


var coll = [1, 2, 3];

var sum = 0;

for ( var i in coll ) {
    sum += coll[i];
}

Nothing special here, and this is what any Javascript developer learn at loop lesson.

Because this method is introduced as basic method, so it becomes pretty popular methods for many developers.

In facts, I’ve seen lots of code written using this method.

In addition to this basic for, you can also use while, do..while .

There is not much different among them.


var coll = [1, 2, 3];

var sum = 0, i = 0;

// Using while
while( i < 3 ) {
    sum += coll[i];
    ++i;
}

// Using do..while
do {
    sum += coll[i];
    ++i;
} while (i < 3);

Using array forEach()

This is a very convenient function created for Javascript for easy iteration. I’m not discussing about its definition, if you want to see detail, read this page.

Let see how it works through following example.


var coll = [1, 2, 3];

var sum = 0;

coll.forEach(function (e) {
    sum += e;
});

Don’t forget that It works fine for array of objects, too.


var dataset = [
   { 'city': 'New York', 'distance': 1024 },
   { 'city': 'Chicago', 'distance': 2048 },
   { 'city': 'Denver', 'distance': 3000 }
];

var total = 0;

dataset.forEach(function (e) {
    total += e.distance;
});

Comparing with for loop, you don’t have to worry about the array index, which can easily lead to off-by-one error.

Wait, just stop right here!

Think about this, do you get off-by-one error often?

If the answer is yes, I think, you should be more careful with the code, or make it safe by starting to use forEach.

Using reduce() function

reduce is a very powerful function. Most of Javascript beginners don’t know how to work with, think it complicated and as a result, forget about it.

Okay, put all things aside, just go straight, use reduce and make Javascript sum array.


var coll = [1, 2, 3];

var sum = coll.reduce(function (prev, current) {
    return current + prev;
}, 0);

Applying with an array of object.


var dataset = [
   { 'city': 'New York', 'distance': 1024 },
   { 'city': 'Chicago', 'distance': 2048 },
   { 'city': 'Denver', 'distance': 3000 }
];

var sum = dataset.reduce(function (prev, current) {
    return current.distance + prev;
}, 0);

Does using reduce gain any benefit or performance over foreach or for loop?

Well, this depends on the problem you try to solve. In most cases, all of them result the same.

If you simply just want to avoid variable spoil, I suggest to use Javascript reduce function.

Combining with ES6 arrow function

Javascript ES6 is a new thing, but it is widely applied in most browsers as Javascript keeps growing fast these days.

When using forEach or reduce, you can improve readability by combining with arrow function.


var coll = [1, 2, 3];

// forEach with arrow function
var sum = 0;
coll.forEach( e => sum += e );

// reduce with arrow function
var sum = coll.reduce( (prev, current) => current + prev, 0);

Evil eval()

Have you ever heard about this eval() function?

It is an evil function. You can search more about it via Google.

So how to apply it to calculate sum for array?

It works like this.


var coll = [1, 2, 3];

var sum = eval( coll.join('+') );

What eval function does is, it will try to execute Javascript string statement and return the result.

So whatever valid Javascript put into eval() as parameter will be executed.

It is so powerful but also evil. So don’t use unless you know what you’re doing.

Generally speaking,

These are known and common methods.

If you ask me, what is my preferred method? I will say, I would go with using reduce function.

Because it is readable and easy to write.

This Javascript sum array is just an example of how to use various methods to handle array data.

These methods can similarly be applied for many kinds of data manipulation. As you have more experiences with Javascript, you will find them very helpful in your Javascript development journey.

Finally, if you like this tutorial, please subscribe or follow us on FacebookTwitterGoogle+ and Youtube to get updates on latest programming tutorials.