-1

I'm using Javascript, and I have an array like this:

counters: [
      { id: 1, value: 0 },
      { id: 2, value: 10 },
      { id: 3, value: 5 },
      { id: 4, value: 3 }
    ]

I want to get a variable total, with the sum of every value field in the counters array. Right now I'm doing:

Total() {
    let total = 0;
    for (let i = 0; i < counters.length; i++) {
      total += counters[i].value;
    }
    return total;   
}

Even if that works, I know that there's a better way. I tried reduce method, but I couldn't get what I need. How can I do it?

demo
  • 6,038
  • 19
  • 75
  • 149
David TG
  • 85
  • 3
  • 10
  • 33

4 Answers4

3

You could add the destructured value with Array#reduce.

var object = { counters: [{ id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 }] },
    sum = object.counters.reduce((s, { value }) => s + value, 0);

console.log(sum);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

const  counters = [
       { id: 1, value: 0 },
       { id: 2, value: 10 },
       { id: 3, value: 5 },
       { id: 4, value: 3 }
     ]
     
 const total = counters.map(x => x.value).reduce((a,c) => a +c)
 
 console.log(total)
     
     

map your array to represent only the value property and use reduce

 const total = counters.map(x => x.value).reduce((a,c) => a + c)
Dupocas
  • 20,285
  • 6
  • 38
  • 56
2

You can do it with reduce, simply pass in a default value of 0:

counters = [
       { id: 1, value: 0 },
       { id: 2, value: 10 },
       { id: 3, value: 5 },
       { id: 4, value: 3 }
     ]
     
total = counters.reduce((accumulator, counter) => accumulator + counter.value, 0);

console.log(total);
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
1

the simplest way is to use reduce method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce ;)

const total = counters.reduce((acc, curr) => acc + curr.value, 0);