The challenge
Write topPlayers(players, n) that returns the names of the n players with the highest score, best first, formatted like "1. Mia (95)". Don’t change the original array!
topPlayers([{ name: "Omar", score: 80 }, { name: "Mia", score: 95 }], 1)
// ["1. Mia (95)"]
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
topPlayers([{ name: "Omar", score: 80 }, { name: "Mia", score: 95 }, { name: "Zoe", score: 88 }], 2)gives["1. Mia (95)", "2. Zoe (88)"]topPlayers([{ name: "Sam", score: 10 }], 5)gives["1. Sam (10)"]- The original array keeps its order:
(() => { const p = [{ name: "B", score: 1 }, { name: "A", score: 2 }]; topPlayers(p, 2); return p[0].name; })()gives"B"
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
sort changes the array it’s called on, so copy first: [...players].sort(…).
Hint 2
Then .slice(0, n) and .map((p, i) => …). The index is the second argument of map’s callback.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function topPlayers(players, n) {
return [...players]
.sort((a, b) => b.score - a.score)
.slice(0, n)
.map((p, i) => `${i + 1}. ${p.name} (${p.score})`);
}
Learn what you need
This exercise uses what Grade 10: Array Power Tools: map, filter & reduce teaches. Read those notes first if any of it is new.