Concept: Reduce pattern to sum numbers (using for loop)
Create a TotalScore component that:
[85, 92, 78, 90, 88]Scores: 85, 92, 78, 90, 88
Total: 433
export default function TotalScore() {
const scores = [85, 92, 78, 90, 88];
// Calculate total using a for loop
return (
<div>
{/* Display scores and total */}
</div>
);
}
let total = 0total = total + scores[i] (or total += scores[i])export default function TotalScore() {
const scores = [85, 92, 78, 90, 88];
// REDUCE: Sum all scores using a for loop
let total = 0;
for (let i = 0; i < scores.length; i++) {
total = total + scores[i];
}
return (
<div>
<p>Scores: {scores.join(', ')}</p>
<p>Total: {total}</p>
</div>
);
}
.reduce() does under the hood!Note: Learn more about the built-in .reduce() method at MDN: Array.reduce()
Try calculating:
total / scores.length