Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate sum of object keys in array - javascript

Question

I am working with firebase and react native.

I have returned an array from my firebase database that looks like this.

[Object, Object, Object]

Under each object I have returned a single item, "level:4".

So I have three objects containing 4,5,6. How do I sum these together?

Thanks!

like image 266
gbland777 Avatar asked Sep 09 '16 01:09

gbland777


People also ask

How do you sum values in array of objects?

To sum a property in an array of objects: Initialize a sum variable, using the let keyword and set it to 0 . Call the forEach() method to iterate over the array. On each iteration, increment the sum variable with the value of the object.

How do you get the sum of all of the items in an array JavaScript?

Use the for Loop to Sum an Array in a JavaScript Array length; i++) { sum += array[i]; } console. log(sum); We initialize a variable sum as 0 to store the result and use the for loop to visit each element and add them to the sum of the array.


4 Answers

You can use Javascript's reduce function. This is basically the same as @epascarello answer but in ES6 syntax.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

const arr = [{level:2},{level:4},{level:5}]; 

const total = arr.reduce((prev,next) => prev + next.level,0);

console.log(total);
like image 149
Yasin Yaqoobi Avatar answered Nov 03 '22 04:11

Yasin Yaqoobi


Either a simple loop

var a = [{level:1},{level:2},{level:3},{level:4}],
        total = 0;
    for (var i=0; i<a.length; i++) {
        total += a[i].level;
    }
console.log('total', total)

or reduce

var a = [{level:1},{level:2},{level:3},{level:4}]
console.log(a.reduce( function(cnt,o){ return cnt + o.level; }, 0))
like image 40
epascarello Avatar answered Nov 03 '22 05:11

epascarello


This code will calculate the sum of an array. First, declare one variable; this variable's name will be sum. sum contains the total's sum. Second, declare a numbers variable of type Array. This variable will contain digits.

Then we start a loop (for) operation, in which we assign to the sum variable the value of (sum= sum+i);. Then we show in (document.write) the numbers and sum.

var summa = 0 , i ;
var numbers= [1,2,3,4,5];
for(i = 0; i <= numbers.length; i++){
    summa=summa+i;
} 
document.write(numbers , ": bu reqemlerin cemi " ,"=" , summa);
like image 36
Javidan Akberov Avatar answered Nov 03 '22 04:11

Javidan Akberov


Use Array.prototype.forEach() method to iterate over your array and sum your elements.

Let us suppose your array is var foo = [object, object, object] Each object has this structure, { level : 4 }

Write code like this:

var sum = 0;
foo.forEach(function(obj){
  sum += obj.level;
});

sum will store the sum

like image 43
Prateek Gupta Avatar answered Nov 03 '22 04:11

Prateek Gupta