user1452494
user1452494

Reputation: 1185

sum a column in a collection of objects in javascript

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.

Upvotes: 0

Views: 5517

Answers (5)

Devank
Devank

Reputation: 159

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))

Upvotes: -1

Knut Marius
Knut Marius

Reputation: 1628

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?

Upvotes: 3

Stefanov.sm
Stefanov.sm

Reputation: 13049

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];
    }

Upvotes: 0

pete
pete

Reputation: 25091

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/

Upvotes: 1

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

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);

Upvotes: 3

Related Questions