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. 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
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
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
"array"
you might want to use an actual array instead. 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.