简体   繁体   中英

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. 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

  1. Since you are calling the object "array" you might want to use an actual array instead.
  2. Creating some functions to abstract away the complexity will help you understand your code better, when you come back to it in the future.

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM