+ 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
3 Respostas
+ 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
+ 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);
0
Giorgos D why same thing not happening with ternary operator