Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  27] [ 3]  / answers: 1 / hits: 23476  / 6 Years ago, wed, january 31, 2018, 12:00:00

Let's say I have a array that contains a multiple object like:



var arr = [{ 'credit': 1, 'trash': null }, { 'credit': 2, 'trash': null}]


I want to get a sum of all credit value from arr array. so expected sum value is 3. so I used this code:



arr.reduce((obj, total) => obj.credit + total)



but when I run this, I get 1[object Object] which is really weird.



Ps: I'm trying to implement this using ES6 not ES5


More From » arrays

 Answers
7

Two problems: your total and obj arguments are backwards, and you need to provide something to initialize the total variable (that's the ,0 part)



arr.reduce((total, obj) => obj.credit + total,0)
// 3

[#55301] Sunday, January 28, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lailab

Total Points: 706
Total Questions: 102
Total Answers: 95

Location: Falkland Islands
Member since Mon, Jul 13, 2020
4 Years ago
;