Concept: Reduce pattern to find average (using for loop)
Create an AverageRating component that:
[4.5, 5.0, 3.5, 4.0, 4.5, 5.0]Ratings: 4.5, 5.0, 3.5, 4.0, 4.5, 5.0
Average: 4.4
⭐⭐⭐⭐
export default function AverageRating() {
const ratings = [4.5, 5.0, 3.5, 4.0, 4.5, 5.0];
// Calculate average using a for loop
// Create star display
return (
<div>
{/* Display ratings, average, and stars */}
</div>
);
}
.toFixed(1) to round to 1 decimal placeMath.round() to get full star count.repeat() to repeat star emojiexport default function AverageRating() {
const ratings = [4.5, 5.0, 3.5, 4.0, 4.5, 5.0];
// REDUCE: Sum all ratings using a for loop
let total = 0;
for (let i = 0; i < ratings.length; i++) {
total = total + ratings[i];
}
// Calculate average
const average = total / ratings.length;
// Create star display (rounded to nearest whole number)
const starCount = Math.round(average);
const stars = '⭐'.repeat(starCount);
return (
<div>
<p>Ratings: {ratings.join(', ')}</p>
<p>Average: {average.toFixed(1)}</p>
<p>{stars}</p>
</div>
);
}
.toFixed(1) formats number to 1 decimal placeMath.round() rounds to nearest integer.repeat(n) repeats string n timesNote: Learn more about the built-in .reduce() method at MDN: Array.reduce()
Try: