0

I have an array of objects that looks like this

[{value: '20'},{value: '20'},{value: '30'}]

I want to sum all the values in a variable like this

sum = array.GetAllObjectsValues; //output: 70
Hadi abdallah
  • 31
  • 1
  • 1
  • 8
  • 3
    Please include your attempt to solve this yourself. – James May 27 '22 at 16:46
  • 1
    Also, search before asking. Example using reduce [here](https://bobbyhadz.com/blog/javascript-get-sum-of-array-object-values). – jarmod May 27 '22 at 16:53
  • Does this answer your question? [Better way to sum a property value in an array](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array) – Heretic Monkey Mar 24 '23 at 13:37

3 Answers3

5

Use Array.reduce to calculate the sum

const sum = array.reduce((acc, o) => acc + parseInt(o.value), 0)
Ionut Achim
  • 937
  • 5
  • 10
0

You can use reduce and Number.parseInt

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.

[{value: '20'},{value: '20'},{value: '30'}].reduce((acc, current) => acc + Number.parseInt(current.value), 0)

Reduce: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

Number parse Int: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Number/parseInt

0

You could do it with jquery

const array = [{value: '20'},{value: '20'},{value: '30'}];

Inside a $.each you can iterate thru this array of objects

var sum = 0;//Initial value hast to be 0
$.each(array, function(key, value) {
    var number = parseFloat(value.value);//Convert to numbers with parseFloat
    sum += number;//Sum the numbers
});

console.log(sum);//Output 70

Edit: Or if you don't want to use jquery, this is another solution with pure js

var sum = 0;//Initial value hast to be 0
for (let i = 0; i < array.length; i ++) {
    var number = parseFloat(array[i].value);//Convert to numbers with parseFloat
    sum += number;//Sum the numbers
}

console.log(sum);//Output 70
Chris G
  • 1,598
  • 1
  • 6
  • 18