add values inside of nested array and keep the index position

72 views Asked by At

I need a way to add the numbers inside the nested array and the total of each array pushed into a new array. Below is my code, but my code only adds the value inside the nested array one by one and then pushes into the new array. For example:

var array = [ [ 1, 3 ], [ 6, 4, 3 ], [ 3, 7, 9 ], [ 9, 0 ], [ 1, 9, 5 ], [ 5, 0 ], 
[ 6, 1 ], [ 0, 2 ], [ 4, 6, 8 ], [ 8, 1 ] ];

var result = 0
var resultArr = [];

  for(var x = 0; x < array.length; x++) {
    for(var y = 0; y < array[x].length; y++) {
      result += array[x][y];
      resultArr.push(result);
    }
  }

console.log(resultArr);

my resultArr prints out

[ 1, 4, 10, 14, 17, 20, 27, 36, 45, 45, 46, 55, 60, 65, 65, 71, 
72, 72, 74, 78, 84, 92, 100, 101 ]

I need to a way so that it adds like below.

[1, 3] = 4
[6, 4, 3] = 13
[3, 7, 9] = 19
[9, 0] = 9
[1, 9, 5] = 15
[5, 0] = 5
[6, 1] = 7
[0, 2] = 2
[4, 6, 8] = 18
[8, 1] = 9

and the result array will be

[4, 13, 19, 9, 15, 5, 7, 2, 18, 9]
2

There are 2 answers

0
Walter Chapilliquen - wZVanG On

Try:

//

var array = [ [ 1, 3 ], [ 6, 4, 3 ], [ 3, 7, 9 ], [ 9, 0 ], [ 1, 9, 5 ], [ 5, 0 ], [ 6, 1 ], [ 0, 2 ], [ 4, 6, 8 ], [ 8, 1 ] ];
var resultArr = [];

for(var i = 0; i < array.length; i++){
 var sum = 0;
 for(var j = 0; j < array[i].length; j++){
  sum += array[i][j]
 }
 resultArr.push(sum)
}

document.write(JSON.stringify(resultArr, null, 2))

0
Lumi Lu On

try this,

var array = [ [ 1, 3 ], [ 6, 4, 3 ], [ 3, 7, 9 ], [ 9, 0 ], [ 1, 9, 5 ], [ 5, 0 ], 
[ 6, 1 ], [ 0, 2 ], [ 4, 6, 8 ], [ 8, 1 ] ];


var resultArr = [];

  for(var x = 0; x < array.length; x++) {
    var result = 0
    for(var y = 0; y < array[x].length; y++) {
      result += array[x][y];
    }
    resultArr.push(result);
  }

console.log(resultArr);

demo in fiddle