Last active
July 25, 2022 06:54
-
-
Save ekrem-aktas/ce11285100b0f29b9a1dc511707ae68c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const basket = [ | |
{ name:"apple", type: "fruit", calories: 52 }, | |
{ name:"broccoli", type: "vegetable", calories: 45 }, | |
{ name:"banana", type: "fruit", calories: 89 } | |
]; | |
// Try to understand acc without looking at the last line | |
const { avgCalories } = basket.reduce((acc, food) => { | |
if (food.type !== "fruit"){ | |
return acc; | |
} | |
const fruitCount = acc.fruitCount + 1; | |
const avgCalories = (acc.avgCalories * acc.fruitCount + food.calories) / fruitCount; | |
return { fruitCount, avgCalories }; | |
}, { fruitCount: 0, avgCalories: 0 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment