9

We have arrays:

[1, 2, 3, 0]
[1, 2, 3]
[1, 2]

Need to get a one array, indexes which is will be like a sum of columns. Expected result:

[3, 6, 6, 0]
1
  • Sometimes you get lucky and people don't even question the fact that you showed no efforts whatsoever. You got lucky ;) Commented Mar 30, 2016 at 10:08

4 Answers 4

15

You can use Array.prototype.reduce() in combination with Array.prototype.forEach().

var array = [
        [1, 2, 3, 0],
        [1, 2, 3],
        [1, 2]
    ],
    result = array.reduce(function (r, a) {
        a.forEach(function (b, i) {
            r[i] = (r[i] || 0) + b;
        });
        return r;
    }, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Sign up to request clarification or add additional context in comments.

8 Comments

How does it happen ?
it iterates over the outer array and then adds each value of the inner array to the same position in the result array.
@NinaScholz reduce, my favorite!
I don't figure out what should I change to make this for rows instead of columns. Probably table.reduce(function (r, a) { r.forEach(function(b, i) { a[i] = (a[i] || 0) + b; }); return a; }, []); is not the right way.
@user3654571 it's not the right place to ask in comments another problem, but you could map the sums with result = array.map(function (aa) { return aa.reduce(function (a, b) { return a + b; }); });
|
10

Basic for loop,

var arr = [[1, 2, 3, 0],[1, 2, 3],[1, 2]];
var res = [];

for(var i=0;i<arr.length;i++){
 for(var j=0;j<arr[i].length;j++){
  res[j] = (res[j] || 0) + arr[i][j];
 }
}

console.log(res); //[3, 6, 6, 0]

Comments

3
function arrayColumnsSum(array) {
  return array.reduce((a, b)=> // replaces two elements in array by sum of them
    a.map((x, i)=>             // for every `a` element returns...
      x +                      // its value and...
      (b[i] || 0)              // corresponding element of `b`,
                               // if exists; otherwise 0
    )
  )
}

console.log(arrayColumnsSum([
  [1, 2, 3, 0]
 ,[1, 2, 3]
 ,[1, 2]
]))

1 Comment

awsome, Thnks :)
2

You can do something like this using map() and reduce()

// function to get sum of two array where array length of a is greater than b
function sum(a, b) {
  return a.map((v, i) => v + (b[i] || 0))
}

var res = [
  [1, 2, 3, 0],
  [1, 2, 3],
  [1, 2]
  // iterate over array to reduce summed array
].reduce((a, b) => a.length > b.length ? sum(a, b) : sum(b, a))


document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.