Project: leaderboard
JavaScript · Unit 10: More on functions
- Full plan
- JavaScript
- Project
- 3 exercises
Your leaderboard sorts the players from most to fewest points. Remember that sort changes the array: sort a copy made with [...].
And something new: map passes your arrow a second piece of data, each element's position, counting from 0.
const players = [
{ name: "Leo", pts: 12 },
{ name: "Ann", pts: 15 },
];
const board = [...players].sort(
(a, b) => b.pts - a.pts
);
const lines = board.map(
(p, i) => `${i + 1}. ${p.name}`
);
console.log(lines);
console.log(players[0].name);Prints
[ '1. Ann', '2. Leo' ] Leo
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Complete the code
Fill in
compare: whoever has more points goes first and, if they're tied, alphabetical order. It should print Ann, Leo and Mia.2. Write the code
Write
rank(players), which returns the players in leaderboard order: whoever has more points first and, if they're tied, in alphabetical order. Sort a copy, so you don't mess up the original list.3. Write the code
You already have
rank. Writestandings(players), which returns an array of strings like "1. Ann (15)", one per player, in leaderboard order.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.