Concept: Reduce pattern to count (using for loop)
Create a CategoryCount component that:
const items = [
{ name: 'Apple', category: 'Fruit' },
{ name: 'Carrot', category: 'Vegetable' },
{ name: 'Banana', category: 'Fruit' },
{ name: 'Broccoli', category: 'Vegetable' },
{ name: 'Orange', category: 'Fruit' }
];
```
</code></pre> Fruit: 3 Vegetable: 2
## Starter Code
jsx export default function CategoryCount() { const items = [ { name: āAppleā, category: āFruitā }, { name: āCarrotā, category: āVegetableā }, { name: āBananaā, category: āFruitā }, { name: āBroccoliā, category: āVegetableā }, { name: āOrangeā, category: āFruitā } ];
// Count items by category using a for loop
return ( <div> {/* Display counts */} </div> ); }
## Hints
- Create variables to count each category: `let fruitCount = 0;`
- Loop through items and increment the appropriate counter
- Use if statements to check category
## Solution
<details>
<summary>Click to reveal solution</summary>
jsx export default function CategoryCount() { const items = [ { name: āAppleā, category: āFruitā }, { name: āCarrotā, category: āVegetableā }, { name: āBananaā, category: āFruitā }, { name: āBroccoliā, category: āVegetableā }, { name: āOrangeā, category: āFruitā } ];
// REDUCE: Count items by category using a for loop let fruitCount = 0; let vegetableCount = 0;
for (let i = 0; i < items.length; i++) { if (items[i].category === āFruitā) { fruitCount = fruitCount + 1; } else if (items[i].category === āVegetableā) { vegetableCount = vegetableCount + 1; } }
return ( <div> <p>Fruit: {fruitCount}</p> <p>Vegetable: {vegetableCount}</p> </div> ); } ```
</details>
Note: Learn more about the built-in .reduce() method at MDN: Array.reduce()
Try: