我需要计算对象数组中的列总和

时间:2019-07-26 14:36:39

标签: javascript arrays sum

我有一个二维数组,单元格是一个对象{id,amount},您需要添加列总和,而仅使用方法。我做了什么-

let matrix = [
    [{id:1, amount:11},{id:2, amount:22},{id:3, amount:33}],
    [{id:4, amount:44},{id:5, amount:55},{id:6, amount:66}],
    [{id:7, amount:77},{id:8, amount:88},{id:9, amount:99}],
    [{id:10, amount:100},{id:11, amount:111},{id:12, amount:112}],
];

let c = matrix.reduce((acc, cur)=> {
    return acc.map((item, index)=> {
        return item + cur[index].amount;
    })
});
console.log(c);

4 个答案:

答案 0 :(得分:2)

为什么不先使用flatMap然后使用reduce

let matrix = [
        [{id:1, amount:11},{id:2, amount:22},{id:3, amount:33}],
        [{id:4, amount:44},{id:5, amount:55},{id:6, amount:66}],
        [{id:7, amount:77},{id:8, amount:88},{id:9, amount:99}],
        [{id:10, amount:100},{id:11, amount:111},{id:12, amount:112}],
    ];
let result = matrix.flatMap(it => it).reduce((acc, item) => acc + item.amount, 0);
console.log(result)

答案 1 :(得分:0)

您可以创建一个长度等于数组宽度的数组。然后使用嵌套的forEach将值添加到相应的元素。

let matrix = [
        [{id:1, amount:11},{id:2, amount:22},{id:3, amount:33}],
        [{id:4, amount:44},{id:5, amount:55},{id:6, amount:66}],
        [{id:7, amount:77},{id:8, amount:88},{id:9, amount:99}],
        [{id:10, amount:100},{id:11, amount:111},{id:12, amount:112}],
    ];

let res = Array(matrix[0].length).fill(0)
matrix.forEach(x => {
  x.forEach((y,i) => {
    res[i] += y.amount;
  })
})

console.log(res)

答案 2 :(得分:0)

因此决定,如果有更好的解决方案,我将很高兴看到

getColSumMatrix = matrix =>
    matrix.reduce((acc, cur) =>
      acc.map((value, i) =>
        typeof value == "object"
          ? value.amount + cur[i].amount
          : value + cur[i].amount
      )
    );

答案 3 :(得分:-1)

const summ = matrix.reduce((acc, table) => {
        return (
            acc +
            table.reduce((acc, { amount }) => {
                return acc + amount;
            }, 0)
        );
    }, 0);