[英]Javascript - How to sum the values in such an array?
I have such an array:我有这样一个数组:
let array = {
[1]: {
name: 'test 1',
count: 5
},
[2]: {
name: 'test 2',
count: 3
}
}
How can I sum the values in the "count" column?如何对“计数”列中的值求和? Examples from simple arrays do not work.来自简单 arrays 的示例不起作用。 I currently have such a loop.我目前有这样的循环。 Can it be done somehow better?它可以做得更好吗?
let sum = 0
Object.entries(array).forEach(([key, val]) => {
sum += val.count
});
Use reduce
使用reduce
let array = { 1: { name: "test 1", count: 5, }, 2: { name: "test 2", count: 3, }, }; total = Object.values(array).reduce((t, { count }) => t + count, 0); //t accumulator accumulates the value from previous calculation console.log(total);
if you want to use a forEach
loop like in your method use Object.values()
instead because you only need values to calculate the sum of count如果您想在您的方法中使用forEach
循环,请使用Object.values()
代替,因为您只需要值来计算计数的总和
let array = { 1: { name: "test 1", count: 5 }, 2: { name: "test 2", count: 3 }, }; let sum = 0; Object.values(array).forEach(({ count }) => { sum += count; }); console.log(sum);
Building on top of the answer provided by @Sven.hig建立在@Sven.hig 提供的答案之上
"array"
you might want to use an actual array instead.由于您正在调用 object "array"
,因此您可能希望使用实际数组。 const add = (a, b) => a + b; const sum = arr => arr.reduce(add, 0); const data = [{ name: "test 1", count: 5, }, { name: "test 2", count: 3, } ]; const total = sum( data.map(d => d.count) ); console.log(total);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.