admin管理员组文章数量:1323335
I'm working on a very large array of subarrays full of numbers that I want to reduce into one sum for each subarray.
Example:
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]];
I'm working on a very large array of subarrays full of numbers that I want to reduce into one sum for each subarray.
Example:
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
Share Improve this question asked Sep 30, 2016 at 17:19 user6732041user6732041 1-
arr.map(a => a.reduce((p,c) => p+c))
– Redu Commented Sep 30, 2016 at 17:27
6 Answers
Reset to default 5Try something like this:
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);
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;
})];
});
.reduce
doesn't modify the original array. You can use .map
and return the new value, like this:
var arr = [[1,2,3], [4,5,6]];
var newArr = arr.map(function(item) {
return [item.reduce(function(a, b) {
return a + b;
})];
});
console.log(newArr);
Or with map and arrow functions:
var arr = [[1,2,3], [4,5,6]];
var result = arr.map(item => item.reduce((a, b) => a + b));
console.log(result); // [ 6, 15 ]
ES5 Syntax
var arr = [[1,2,3], [4,5,6]];
arr.map(function (item) {
return item.reduce(function (a, b) {
return a+b;
});
})
ES6 Syntax
arr.map(item => {
return item.reduce((a,b) => a+b);
})
If you want the summed result to be in their own list, I would break the problem down in to 2 steps:
const arr = [[1,2,3], [4,5,6]];
const sumList = (xs) => [xs.reduce((x, y) => x + y, 0)];
alert(arr.map(sumList)); //=> [[6], [15]]
Maybe this is what you want?
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);
本文标签: javascriptFinding the sum of subarraysStack Overflow
版权声明:本文标题:javascript - Finding the sum of subarrays - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742137236a2422423.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论