找到子阵列的总和

时间:2016-09-30 17:19:26

标签: javascript arrays

我正在处理一大堆充满数字的子数组,我希望每个子数组减少为一个数。

示例:

bool operator<(const screenPoint& left, const screenPoint& right) {
    return left.x < right.x ||
           ( left.x == right.x && left.y < right.y );
}

我的解决方案只返回原始数组元素

6 个答案:

答案 0 :(得分:4)

尝试这样的事情:

var arr = [[1,2,3], [4,5,6]];
var newArr = [];

arr.forEach(function(item) {
  item = item.reduce(function(a, b) {
    return a + b;
  });
  newArr.push([item]);
});
console.log(newArr);

为了更简洁,您可以使用传递给forEach回调的值:您当前正在迭代的项目,该项目的索引以及数组本身:

arr.forEach(function(item, index, array) {
  array[index] = [array[index].reduce(function (a, b) {
    return a + b;
  })];
});

答案 1 :(得分:2)

struct buffer { FILE *file; int size; }; 不会修改原始数组。您可以使用.reduce并返回新值,如下所示:

.map

答案 2 :(得分:0)

或使用地图和箭头功能:

var arr = [[1,2,3], [4,5,6]];
var result = arr.map(item => item.reduce((a, b) => a + b));
console.log(result); // [ 6, 15 ]

答案 3 :(得分:0)

ES5语法

var arr = [[1,2,3], [4,5,6]];

arr.map(function (item) {
  return item.reduce(function (a, b) {
    return  a+b;
  });
})

enter image description here

ES6语法

arr.map(item => {
  return item.reduce((a,b) => a+b);
})

enter image description here

答案 4 :(得分:0)

也许这就是你想要的?

&#13;
&#13;
var arr = [[1,2,3], [4,5,6]];

arr = arr.map(function(item,i) {
  return [item.reduce(function(a, b) {
    return a + b;
  })];
});
console.log(arr);
&#13;
&#13;
&#13;

答案 5 :(得分:0)

如果您希望求和结果在他们自己的列表中,我会将问题分解为两步:

const arr = [[1,2,3], [4,5,6]];
const sumList = (xs) => [xs.reduce((x, y) => x + y, 0)];

alert(arr.map(sumList)); //=> [[6], [15]]

相关问题