查找子数组的总和 [英] Finding the sum of subarrays

查看:97
本文介绍了查找子数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个非常大的子数组数组,这些子数组的数字我想将每个子数组减少为一个总和.

I'm working on a very large array of subarrays full of numbers that I want to reduce into one sum for each subarray.

示例:

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

arr.forEach(function(item) {
  item.reduce(function(a, b) {
    return a + b;
  });
});
console.log(arr);

//I want arr to equal [[6], [15]];

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

My solution just returns the original array element

推荐答案

尝试如下操作:

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回调的值:当前正在迭代的项目,该项目的索引以及数组本身:

To be a bit more concise, you can use the values passed to the forEach callback: the item you're currently iterating through, the index of that item, and the array itself:

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

这篇关于查找子数组的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆