查找子数组的总和

编程入门 行业动态 更新时间:2024-10-15 10:21:40
本文介绍了查找子数组的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

查找子数组的总和

本文发布于:2023-11-29 11:53:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646325.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   总和

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!