我们有阵列:
[1, 2, 3, 0]
[1, 2, 3]
[1, 2]
需要获得一个数组,索引将类似于列的总和。预期结果:
[3, 6, 6, 0]
答案 0 :(得分:10)
您可以将Array.prototype.reduce()
与Array.prototype.forEach()
结合使用。
var array = [
[1, 2, 3, 0],
[1, 2, 3],
[1, 2]
],
result = array.reduce(function (r, a) {
a.forEach(function (b, i) {
r[i] = (r[i] || 0) + b;
});
return r;
}, []);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:1)
// function to get sum of two array where array length of a is greater than b
function sum(a, b) {
return a.map((v, i) => v + (b[i] || 0))
}
var res = [
[1, 2, 3, 0],
[1, 2, 3],
[1, 2]
// iterate over array to reduce summed array
].reduce((a, b) => a.length > b.length ? sum(a, b) : sum(b, a))
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
答案 2 :(得分:1)
基本的循环,
var arr = [[1, 2, 3, 0],[1, 2, 3],[1, 2]];
var res = [];
for(var i=0;i<arr.length;i++){
for(var j=0;j<arr[i].length;j++){
res[j] = (res[j] || 0) + arr[i][j];
}
}
console.log(res); //[3, 6, 6, 0]
答案 3 :(得分:0)
function arrayColumnsSum(array) {
return array.reduce((a, b)=> // replaces two elements in array by sum of them
a.map((x, i)=> // for every `a` element returns...
x + // its value and...
(b[i] || 0) // corresponding element of `b`,
// if exists; otherwise 0
)
)
}
console.log(arrayColumnsSum([
[1, 2, 3, 0]
,[1, 2, 3]
,[1, 2]
]))