如何计算多个数组的总和? [英] How to calculate the sum of multiple arrays?

查看:70
本文介绍了如何计算多个数组的总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决一个方程,在该方程中,我从索引后的数组列表中添加数字.

I am trying to solve an equation where I add numbers from a list of arrays following the indices.

列表的每个数组都是随机生成的 4 个数字的固定长度数组,如下所示:

Each array of a list are a randomly generated fixed-length array of 4 numbers like so:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

所以我想要做的是从每个数组中获取每个索引的每个数字的总和.像这样:

So what I am trying to do is get the sum of each number of each index from each array. Like so:

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
]

// expectedResult = [8, 19, 18, 7];

我怎样才能做到这一点?

How can I achieve this?

推荐答案

这是另一种使用 map() 在第一个数组上,嵌套有 reduce() 生成相应列的总数.

This is another approach that uses map() over the first array, nested with a reduce() that generated the total of the corresponding column.

const list = [
  [2, 9, 1, 2],
  [2, 3, 9, 4],
  [4, 7, 8, 1]
];

const sums = list[0].map((x, idx) => list.reduce((sum, curr) => sum + curr[idx], 0));

console.log(sums);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

这篇关于如何计算多个数组的总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆