0

I have a collection of array-like objects like this :

a = [[1,2],[3,4],[5,6],[7,8]]

And I would like to sum the columns (if u think of this as a 4x2 array) such that:

col1_sum = 16
col2_sum = 20

What is the best way of doing this is JS?

I tried using underscore's _.reduce function like so:

var col1_sum =_.reduce(a, function(memo,obj){ return memo + parseFloat(obj[0]);},0)

but I get an "undefined" error

any ideas? thank you.

Kousik
  • 21,485
  • 7
  • 36
  • 59
user1452494
  • 1,145
  • 5
  • 18
  • 40

5 Answers5

3

You could always kick it old school. It's not pretty, but it works.

col1_sum = 0;
col2_sum = 0;
for (var i = 0; i < a.length; ++i) {
    col1_sum += a[i][0];
    col2_sum += a[i][1];
}

My other thought was to use jQuery's each function, but I guess you're not looking for a jQuery solution?

EDIT - Who needs jQuery.each? Just use JavaScript's Array.forEach:

var col1_sum = 0;
var col2_sum = 0;

a = [[1,2],[3,4],[5,6],[7,8]];
a.forEach(function(element, index, array) { col1_sum += element[0]; col2_sum += element[1]; });

alert(col1_sum);
alert(col2_sum);
Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
3

I made a simple jsfiddle from your underscore reduce code, and it seems to be working fine: http://jsfiddle.net/PdL5P/

var a = [[1,2],[3,4],[5,6],[7,8]]

var col1_sum = _.reduce(a, function(memo,obj){ return memo + parseFloat(obj[0]); }, 0 );

$("#sum").html(col1_sum)

Are you sure that "a" is defined at that point of your code?

Knut Marius
  • 1,588
  • 18
  • 40
1

You can also kick it new school:

var sumColumnJS = function sumColumnJS(array, col) {
    var sum = 0;
    array.forEach(function (value, index, array) {
        sum += value[col];
    });
    return sum;
};

or use the _.each array iterator:

sumColumn_ = function sumColumn_(array, col) {
    var sum = 0;
    _.each(a, function (item) {
        sum += item[col];
    });
    return sum;
};

Working demo: http://jsfiddle.net/HTqvf/

pete
  • 24,141
  • 4
  • 37
  • 51
0

Simple iteration, as in any traditional language

    var col1_sum = 0, col2_sum = 0, row;
    for (row in a)
    {
        col1_sum += a[row][0];
        cos2_sum += a[row][1];
    }
Stefanov.sm
  • 11,215
  • 2
  • 21
  • 21
  • You probably shouldn't use `for...in` on an array, though. See, e.g. http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Scott Mermelstein Jul 09 '13 at 21:16
-1

I would do this.

a = [[1,2],[3,4],[5,6],[7,8]]
col1_sum = _.sum(_.map(a,0))
col2_sum = _.sum(_.map(a,1))
Devank
  • 159
  • 2
  • 9