0

loop in array object

I have one array object I want to sum scores field in all items with reduce but i got wrong result what is reason? My code: const obj = [ { name: "a", family: "e", score: 10 }, { name: "b", family: "f", score: 5 }, { name: "c", family: "g", score: 3 }, { name: "d", family: "h", score: 19 } ]; document.getElementById("p2").innerHTML = obj.reduce(myFunction); function myFunction(total, value) { return total + value.score; } "p2" is a <p> tag. Link: https://code.sololearn.com/WvV6p7E0TN2U

18th Jul 2022, 12:01 PM
Hadi
Hadi - avatar
5 Answers
+ 2
<total> in myFunction is the accumulator, and it is a Number, initialized by zero, not an object. You only need to add <value.score> to <total> as you did in your post Description. return total + value.score; // correct //return total.score + value.score; //wrong
18th Jul 2022, 3:35 PM
Ipang
+ 4
You can link your code link this: Go to Code section, click +, select the programming language, insert your code, save. Come back to the thread, click +, Insert Code, sort for My Code Bits, select your code. This way other users can test your code.
18th Jul 2022, 1:12 PM
Lisa
Lisa - avatar
+ 2
Apart from the function that handles the accumulation (reduction), you also need to provide an initial accumulator value, which is the second argument to be given to reduce() obj.reduce( myFunction, 0 ); Here initial accumulator value will be zero (second argument). reduce() calls myFunction for each element, and assign the value returned by myFunction to the accumulator.
18th Jul 2022, 1:21 PM
Ipang
+ 1
by initial accumulator value got NaN also.
18th Jul 2022, 2:04 PM
Hadi
Hadi - avatar
+ 1
ok thanks
19th Jul 2022, 3:03 AM
Hadi
Hadi - avatar