codex-lv3-may-2025

Kata 10: Calculate Average Rating

Concept: Reduce pattern to find average (using for loop)

Challenge

Create an AverageRating component that:

  1. Has an array of product ratings: [4.5, 5.0, 3.5, 4.0, 4.5, 5.0]
  2. Calculates the average rating using a for loop
  3. Displays the average rounded to 1 decimal place
  4. Shows a star rating (⭐ for each full star)

🔗 Practice on CodeSandbox

Expected Output

Ratings: 4.5, 5.0, 3.5, 4.0, 4.5, 5.0
Average: 4.4
⭐⭐⭐⭐

Starter Code

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>
  );
}

Hints

Solution

Click to reveal solution
export 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>
  );
}

Concept Review

Note: Learn more about the built-in .reduce() method at MDN: Array.reduce()

Challenge Variation

Try:


Back to Kata Index