Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  44] [ 4]  / answers: 1 / hits: 34354  / 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
nathanaelzechariahl questions
Sat, Feb 27, 21, 00:00, 3 Years ago
Thu, Aug 20, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
Fri, Nov 22, 19, 00:00, 5 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
;