AI Hints
Home›JavaScript Tutorial›Practice: Arrays
JavaScript · Lesson 56 of 138

Practice: A Grade Report

Sorting and summarizing.

⏱ 2 min read▶ Video at 1:08:24🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A teacher has a list of students and their scores. They want the class average, the top three students, and the names of anyone who needs extra help, below fifty. Pause, and think about which array methods you'd use.

Practice: A Grade Report
From the video: Practice: A Grade Report
  • Students and scores
  • Average, top three, extra help
  • Which methods?

The report

Reduce adds the scores for the average. To sorted, with B minus A, puts the highest first, without changing the original, and slice takes the top three. Filter and map find the students below fifty. Run it.

app.jsjavascript
const results = [["Ana", 88], ["Ben", 45], ["Cara", 92], ["Dev", 67], ["Eli", 38], ["Fay", 75]];

const avg = results.reduce((t, [, s]) => t + s, 0) / results.length;
const top3 = results.toSorted((a, b) => b[1] - a[1]).slice(0, 3);
const help = results.filter(([, s]) => s < 50).map(([n]) => n);

console.log("Average:", avg.toFixed(1));
console.log("Top 3:", top3.map(([n, s]) => `${n} (${s})`).join(", "));
console.log("Extra help:", help.join(", "));
Output
Average: 67.5
Top 3: Cara (92), Ana (88), Fay (75)
Extra help: Ben, Eli

Thinking in steps

Notice how each question became one line. Combine, sort and slice, filter and map. That's the power of array methods. When you meet a new problem, ask which of these steps it needs. Usually, it's just two or three of them, chained together.

keyvalue
Averagereduce ÷ length
Top 3toSorted + slice
Below 50filter + map
Habitthink in steps

Summary

A grade report came together from reduce, sorting, slice, filter, and map. Next, a quiz on arrays.

Key takeaways
  • reduce for totals
  • toSorted + slice
  • filter + map
Next up: Arrays Quiz — test yourself