Home > Blockchain >  sum all values of an object in an array of objects javascript
sum all values of an object in an array of objects javascript

Time:05-28

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

CodePudding user response:

Use Array.reduce to calculate the sum

const sum = array.reduce((acc, o) => acc   parseInt(o.value), 0)

CodePudding user response:

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

CodePudding user response:

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
  • Related