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.
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.
Share Improve this question edited Jul 9, 2013 at 21:19 Kousik 22.5k7 gold badges38 silver badges60 bronze badges asked Jul 9, 2013 at 21:01 user1452494user1452494 1,1855 gold badges20 silver badges41 bronze badges5 Answers
Reset to default 3You 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);
I made a simple jsfiddle from your underscore reduce code, and it seems to be working fine: http://jsfiddle/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?
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/HTqvf/
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]; }
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))
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744771637a4592794.html
评论列表(0条)