在嵌套数组中添加值并保持索引位置

时间:2015-06-09 00:07:04

标签: javascript arrays sum

我需要一种方法来在嵌套数组中添加数字,并将每个数组的总数推入新数组中。下面是我的代码,但我的代码只是逐个添加嵌套数组中的值,然后推入新数组。例如:

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);

我的resultArr打印出来

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

我需要一种方式,以便添加如下。

[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

,结果数组将是

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

2 个答案:

答案 0 :(得分:1)

尝试:

//

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))

答案 1 :(得分:1)

试试这个,

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);
<{3}}

中的

演示