Learn JavaScript · lesson 36 of 60 · about 10 minutes
Project: Quiz Statistics
Sum up Sam's quiz: drop broken results, then find the average, the best player and who passed.
What you'll learn
- Combine map, filter, reduce and sort
- Format results neatly
- Avoid changing the original data
The quiz results
Lots of visitors have taken Sam's quiz now, and their results arrive as an array of { name, score } objects. Some came through broken, with a score of 120, -5 or the text "80". The statistics first keep only whole numbers from 0 to 100 with filter, then work out the average with reduce, the best player from a sorted copy, and the names of everyone who passed with filter and map.
The plan
1. Keep the valid results with filter
2. If there are none, say so and stop
3. Average the scores with reduce, divided by how many there are
4. Sort a copy by score and take the first: the best player
5. List who passed (60 or more) with filter and map
The statistics
const students = [
{ name: "Ada", score: 91 },
{ name: "Bo", score: 48 },
{ name: "Cy", score: 73 },
{ name: "Di", score: 66 },
];
const scores = students.map((s) => s.score);
const average = scores.reduce((a, b) => a + b, 0) / scores.length;
const passRate = (scores.filter((s) => s >= 50).length / scores.length) * 100;
const board = [...students].sort((a, b) => b.score - a.score);
console.log(`Average: ${average.toFixed(1)}`);
console.log(`High: ${Math.max(...scores)} Low: ${Math.min(...scores)}`);
console.log(`Pass rate: ${passRate}%`);
board.forEach((s, i) => console.log(`${i + 1}. ${s.name} (${s.score})`));
console.log(`Original first: ${students[0].name}`);Output
Average: 69.5
High: 91 Low: 48
Pass rate: 75%
1. Ada (91)
2. Cy (73)
3. Di (66)
4. Bo (48)
Original first: AdaTip
forEach runs a function for every item but returns nothing. Use it for side effects like printing, and map when you want a new array.
Tip
sort keeps items that compare equal in the order they came in, so when two players tie, the one who took the quiz first is the best player.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.