Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Sorting the Table With a Compare Function

Sorting the Table With a Compare Function

The next line of Nadia’s script ranks the teams for the booking site. In this lesson, you ported her first version of that line, which sorts by points, largest first, from Python’s key= to a JavaScript compare function.

Here’s the line, with each team’s name and points, in the table’s alphabetical order:

Language: Python
provisional = [
    {"team": "Albion", "points": 7},
    {"team": "Athletic", "points": 16},
    {"team": "Dynamo", "points": 13},
    {"team": "Rovers", "points": 16},
    {"team": "United", "points": 9},
    {"team": "Wanderers", "points": 13},
]

ranked = sorted(provisional, key=lambda t: -t["points"])
for t in ranked:
    print(t["team"], t["points"])
  • Python prints Athletic and Rovers at the top.
  • Ported line by line, sorted() becomes its JavaScript twin toSorted(), which returns a sorted copy and leaves the original alone. It has no key=, so the function goes straight into the call: provisional.toSorted((t) => -t.points).
  • That port runs without an error and puts Wanderers on top, with 13 points. Athletic, top of Python’s list, come fifth. On Node 26, the order is the alphabetical list turned round; another engine may give another wrong order.
  • A key function answers a question about one team: what do I sort by? A JavaScript sort hands the function two teams, a and b, and asks which comes first. Negative puts a first, positive puts b first, and 0 keeps their order.
  • The port’s function reads only the first team, a: JavaScript drops extra arguments without an error, where a Python lambda raises a TypeError. Minus a’s points is always negative, so every answer says a first, and each team goes in front of the one it’s compared with.
  • Port the key, not the function: compare the points of both teams. The numbers recipe, (a, b) => a - b, sorts smallest first, so for largest first, where Python negated the key, swap a and b: b.points - a.points. Athletic against Albion is 7 minus 16, -9, so Athletic goes first. Rovers against Athletic is 0, so they keep their order.
  • A JavaScript developer names the compare function once and passes the name wherever the table is sorted. The same byPoints sorts the confirmed table too, for the confirmed-leaders line, and sort() takes it too, sorting the array itself.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 Next, Nadia’s script ranks the teams for the booking site. In this lesson, you’ll port it and see what JavaScript’s sort asks for. Her first version sorts by points, largest first.

00:14 The snippet keeps only names and points. The key function returns minus the points, so the most points come first. Python prints Athletic and Rovers at the top.

00:27 Port it line by line. The list of dicts becomes a const array of objects. sorted()’s JavaScript twin is toSorted(), which returns a sorted copy and leaves the original alone.

00:40 It has no key= keyword, so the function goes straight into the call. The lambda turns into an arrow function. The for loop carries over as for...of, and print turns into console.log().

00:55 Both hand a function to the sort, so the port reads like the Python.

01:01 Python put Athletic on top. Which team does the JavaScript port put on top? Your turn: pause the video and predict.

01:14 Run it, and JavaScript puts Wanderers on top, with thirteen points. Athletic, top of Python’s list, come fifth. There’s no error and no warning. On Node 26, the order is the alphabetical list turned round, and another engine may give another wrong order.

01:36 A key function answers a question about one team: what do I sort by? A JavaScript sort hands the function two teams, a and b, and asks which comes first. Negative puts a first, positive puts b first, and zero keeps their order.

01:55 The port’s function reads only the first team, a. JavaScript drops extra arguments without an error, where a Python lambda raises a TypeError.

02:05 Minus a’s points is always negative, so every answer says a first. In this run, each team goes in front of the one it’s compared with, so the last call puts Wanderers on top.

02:20 Port the key, not the function. Compare the points of both teams. The numbers recipe, a minus b, sorts smallest first. For largest first, where Python negated the key, JavaScript swaps a and b: b’s points minus a’s points.

02:39 When Athletic meets Albion, seven minus sixteen is minus nine, so Athletic goes first. When Dynamo meets Athletic, the answer is three, so Athletic stays first.

02:52 Rovers and Athletic both have sixteen, so the answer is zero, and they keep their order.

03:00 Back beside the Python, run it again: JavaScript prints Python’s order.

03:06 A JavaScript developer names this compare function once, byPoints, and passes the name wherever the table is sorted. The same function sorts the confirmed table too, for the confirmed-leaders line.

03:19 And sort() takes it too, sorting the array itself.

03:25 The booking site also lists the teams from A to Z. Subtracting won’t work for text: one name minus another is NaN, so the order stays as it was. For text, the string method localeCompare() does the comparing.

03:41 It returns negative when a comes first in the alphabet, positive when b does, and zero for a tie. Name it byTeam, and the list matches Python’s.

03:53 Watch out for lowercase names. localeCompare() puts the scorer de Souza before Diaz, as str.lower does for these names, where Python’s plain sorted() puts it last.

04:07 The rule to keep: a key function says what to sort by, and a compare function says which of two items comes first. So compare the key for both items. Subtract for numbers, b minus a for largest first, and localeCompare() for text.

04:26 Name the function, and pass it wherever you sort. Up next is Breaking Ties Without Reversing the Sort, where Athletic and Rovers are level on points, and Python’s tuple key puts Rovers first on goal difference.

Become a Member to join the conversation.