I am looking for a pattern to get the totals for each n-th item of arrays. Conceptually this would be like getting column totals of a data table.
var dataRows = [
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33]
]
// The outcome should be:
// [ 60, 63, 66, 69]
I had some equivalent Python code on the server side, but decided it should be handled client side, thus in javascript. Here is the equivalent Python code:
[sum(i) for i in zip(*data_rows)]
How would you go about writing this? I am sure the code will be longer without zip, unpack and list comprehension, but can it be done elegantly? Also are there libraries that extend the core library of JS?
Just iterate over your arrays:
var dataRows = [
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33]
]
var result = [];
for(var i = 0; i < dataRows.length; i++){
for(var j = 0; j < dataRows[i].length; j++){
result[j] = (result[j] || 0) + dataRows[i][j];
} // ^ Add the current value to the proper position of `result`.
}
alert(JSON.stringify(result));
As for the second part of your question:
There are libraries that add a lot of array manipulation functions to JS. Take a look at Underscore, for example.
Play with ES5 array methods:
var dataRows = [
[10, 11, 12, 13],
[20, 21, 22, 23],
[30, 31, 32, 33]
];
dataRows.reduce(function(a, b) {
return a.map(function(el, i) {
return el + b[i];
});
});
// [60, 63, 66, 69]
This is attempt to give a clue, so I didn't deal with error handling thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With