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:
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 twintoSorted(), which returns a sorted copy and leaves the original alone. It has nokey=, 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,
aandb, and asks which comes first. Negative putsafirst, positive putsbfirst, 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 aTypeError. Minusa’s points is always negative, so every answer saysafirst, 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, swapaandb: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
byPointssorts the confirmed table too, for the confirmed-leaders line, andsort()takes it too, sorting the array itself.