Skip to content

Instantly share code, notes, and snippets.

@ekrem-aktas
Last active July 25, 2022 06:54
Show Gist options
  • Save ekrem-aktas/ce11285100b0f29b9a1dc511707ae68c to your computer and use it in GitHub Desktop.
Save ekrem-aktas/ce11285100b0f29b9a1dc511707ae68c to your computer and use it in GitHub Desktop.
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