在JavaScript中获取数组列的总和

Get sum of array columns in JavaScript

本文关键字:数组 JavaScript 获取      更新时间:2023-09-26

我们有数组:

[1, 2, 3, 0]
[1, 2, 3]
[1, 2]

需要获得一个单数组,索引将类似于列的总和。预期结果:

[3, 6, 6, 0]

您可以将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>');

循环基本,

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

您可以使用map()reduce()执行类似操作

// 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>');