Lesson 7 of 8

Sorting by two keys

Goal

Score first, then name

01

Explanation

A leaderboard sorts players by score from highest to lowest, and when two players tie, it sorts them by name alphabetically. That's sorting by two keys: the second key only comes into play when the first one is equal.

A compare function returns a negative number if the first item comes first, a positive number if the second one does, and zero when they're equal. So one line is enough: b.score - a.score || a.name.localeCompare(b.name, 'en'). Since || treats zero as if it were missing, it only moves on to the second key when the scores are equal.

Watch out: comparing names with < compares character codes, not alphabetical order. That puts “Eric” before “Émile”, because the code for “E” is smaller than the code for “É”, even though m comes before r. localeCompare treats É as an E with an accent, so it moves on and compares the letters that follow.

02

Your task

Write sortPlayers(players) to return a new array sorted by score from highest to lowest, then by name in ascending order with localeCompare. Remember that sort changes the original array, so copy it before sorting or use toSorted.

Checks

5 checks
  1. Scores are sorted high to low as numbers, not strings
  2. Tied players are sorted by name
  3. Names follow alphabetical order, not character codes
  4. The original array is unchanged
  5. The leaderboard shows the right order
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/5

Press “Run and check” to grade your code.

5 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.