Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have defined a JavaScript variables called myData which is a new Array like this:

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

I am wondering if it is possible to sum the number values found in the array (ex. 0+0+21+2+0 and so on) and have probably a variable with the result that I can use outside of the script tag because I have 7 of this kind of arrays corresponding for each of the day in the week. I want to make a comparison afterwards based on that. That is the most preferred method for this kind of actions if is possible?

share|improve this question
    
Iterate over the array and add the second elements of the inner arrays. –  Felix Kling Apr 17 '13 at 10:31
add comment

6 Answers

up vote 1 down vote accepted

Try the following

var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];

var myTotal = 0;  //Variable to hold your total

for(var i=0, len=myData.length; i<len; i++){
    myTotal += myData[i][1];  //Iterate over your first array and then grab the second element add the values up
}

alert(myTotal); //22 in this instance
share|improve this answer
    
I think you meant myData[i][1]. And why use parseFloat if the value is already a number anyway? –  Felix Kling Apr 17 '13 at 10:35
    
it output 24156 instead of like it should 3. I've tested with an "empty value array" and I receive the same output... –  Daniela costina Vaduva Apr 17 '13 at 10:37
    
@FelixKling it works with myData[i][1] but how I make myTotal available in other script tag? –  Daniela costina Vaduva Apr 17 '13 at 10:39
    
Daniel, did you fix the typo that Felix Kling pointed out? Rember to write "myData[i][1]" instead of the wrong version: "myData[1]" in the example. –  Silas Hansen Apr 17 '13 at 10:39
    
@FelixKling Thanks have edited, and i guess i was being overprecautius by using parseFloat. Daniela i've tested and it works have a look here - jsbin.com/ibajas/1 –  Mark Walters Apr 17 '13 at 10:39
show 2 more comments

You could use the Array.reduce method:

var sum = myData.reduce(
           function(prev,current){
             return  +(current[1]) + prev;
           }, 0
         );

See MDN

share|improve this answer
    
It should be prev[1] I guess. By all means the result won't give 23. –  VisioN Apr 17 '13 at 10:40
1  
@Kooilnc Please be aware that Array.reduce is an ECMAscript 5 addition so my not be supported by all browsers - see here developer.mozilla.org/en-US/docs/JavaScript/Reference/… which also includes some code which can be implemented to overcome this –  Mark Walters Apr 17 '13 at 10:41
    
@VisioN: forgot the initial value, added it. And no, it shouldn't be prev[1] @MarkWalters: yep, but one can use the shim from the MDN-link (see answer) –  KooiInc Apr 17 '13 at 10:47
add comment

I would use reduce

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0], ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);

var sum = myData.reduce(function(a, b) {
    return a + b[1];
}, 0);

$("#result").text(sum);

Available on jsfiddle

share|improve this answer
add comment

The javascript built-in reduce for Arrays is not a standard, but you can use underscore.js:

var data = _.range(10);
var sum = _(data).reduce(function(memo, i) {return memo + i});

which becomes

var sumMyData = _(myData).reduce(function(memo, i) {return memo + i[1]}, 0);

for your case. Have a look at this fiddle also.

share|improve this answer
add comment

If you want to discard the array at the same time as summing, you could do (say, 'stack' is the array):

        var sum = 0;
        while(stack.lentgh > 0) sum += stack.pop();
share|improve this answer
add comment

If you are looking for a nice modular clean way of doing it, I would say creating a sum method might work nicely, e.g. you could add the sum function to Array

Array.prototype.sum = function(selector) {
    if (typeof selector !== 'function') {
        selector = function(item) {
            return item;
        }
    }
    var sum = 0;
    for (var i = 0; i < this.length; i++) {
        sum += selector(this[i]);
    }
    return sum;
};

then you could do

> [1,2,3].sum()
6

and in your case

> myData.sum(function(item) { return item[1]; });
23
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.