Skip to content

Instantly share code, notes, and snippets.

View ekrem-aktas's full-sized avatar

Ekrem ekrem-aktas

View GitHub Profile
const basket = [
{ name:"apple", type: "fruit" },
{ name:"broccoli", type: "vegetable" }
];
// Add prices to each food in the basket
const basketWithPrices = basket.reduce((acc, food) => acc.concat({ ...food, price: getPrice(food) }), []);
// But Array.map is better for it
const basketWithPrices = basket.map(food => ({ ...food, price: getPrice(food)}));
const basket = [
{ name:"apple", type: "fruit" },
{ name:"broccoli", type: "vegetable" }
];
// Array.reduce can be used to filter fruits
const fruits = basket.reduce((acc, food) => food.type === "fruit" ? acc.concat(food) : acc, []);
// But Array.filter is better for it
const fruits = basket.filter(food => food.type === "fruit");
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;