+ 2

Why 1 instead of { blue:2, brown:1, yellow:1} is obtained as output?

I'm struggling with the 3rd output line, after all why 1 instead of { blue:2, brown:1, yellow:1} is obtained as output? https://code.sololearn.com/cSsCSUgSmxRt/?ref=app

14th Aug 2021, 6:10 AM
Mohd Aadil
Mohd Aadil - avatar
3 Antworten
+ 1
Mohd Aadil Because with ternary operator you actually return the value of acc[something] which is an integer in this case. Then on next iteration the acc is now an integer and acc[something] is undefined so the ternary again returns the integer 1. For various reasons this is true in JS: 123["abc"] === undefined
14th Aug 2021, 11:15 AM
Giorgos
+ 2
Mohd Aadil You need to also return the accumulator: const charactersByEyeColor = characters.reduce((acc, nextCharacter) => { if (acc[nextCharacter.eye_color]) { acc[nextCharacter.eye_color]++; }else{ acc[nextCharacter.eye_color] = 1 } return acc; }, {}); console.log("characters by eye color =>",charactersByEyeColor);
14th Aug 2021, 10:12 AM
Giorgos
0
Giorgos D why same thing not happening with ternary operator
14th Aug 2021, 10:25 AM
Mohd Aadil
Mohd Aadil - avatar