Har*_*ija 1 javascript arrays math
我正在尝试解决一个方程,在该方程中,我从索引后的数组列表中添加数字。
列表的每个数组都是随机生成的 4 个数字的固定长度数组,如下所示:
const list = [
[2, 9, 1, 2],
[2, 3, 9, 4],
[4, 7, 8, 1]
]
Run Code Online (Sandbox Code Playgroud)
所以我想要做的是从每个数组中获取每个索引的每个数字的总和。像这样:
const list = [
[2, 9, 1, 2],
[2, 3, 9, 4],
[4, 7, 8, 1]
]
// expectedResult = [8, 19, 18, 7];
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
这是另一种方法,它在第一个数组上使用map(),嵌套了一个reduce(),生成相应列的总数。
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);Run Code Online (Sandbox Code Playgroud)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}Run Code Online (Sandbox Code Playgroud)
小智 5
const list = [
[2, 9, 1, 2],
[2, 3, 9, 4],
[4, 7, 8, 1],
];
const result = list.reduce((a, b) => a.map((c, i) => c + b[i]));
console.log(result);Run Code Online (Sandbox Code Playgroud)
更新:要求解释。
首先,reduce会给出一个(数组的)数组,并希望将其缩减为单个值(一个数组)。为此,它将调用第一个箭头函数两次。第一次a将为[2,9,1,2],b将为[2,3,9,4]。对于a和b,第一个箭头函数将返回a的映射。如果a是一个数组,它将返回一个数组,其中每个元素都添加到数组b的相应元素中。第一个映射的结果将是[4,12,10,6]。 reduce现在将使用a(第一个映射结果)[4,12,10,6]和b(输入[4,7,8,1]的最终数组元素)第二次调用第一个箭头函数。此箭头函数将执行与之前相同的操作:返回一个数组,其中每个a元素都添加到b的相应元素中。 地图将返回[8,19,18,7]。由于没有更多的输入元素,reduce将返回该值(数组)。