Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  44] [ 4]  / answers: 1 / hits: 34353  / 8 Years ago, fri, september 9, 2016, 12:00:00

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!


More From » reactjs

 Answers
5

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




[#60764] Tuesday, September 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nathanaelzechariahl

Total Points: 745
Total Questions: 86
Total Answers: 103

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
;