Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern for "column total" of an array of arrays

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?

like image 909
Roy Prins Avatar asked Dec 31 '14 09:12

Roy Prins


2 Answers

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.

like image 106
Cerbrus Avatar answered Oct 31 '22 00:10

Cerbrus


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.

like image 39
Leo Avatar answered Oct 31 '22 01:10

Leo