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

Breaking Ties Without Reversing the Sort

Breaking Ties Without Reversing the Sort

By points alone, two pairs of teams in the provisional table are level: Rovers and Athletic on 16, Dynamo and Wanderers on 13. In this lesson, you ported the line of Nadia’s script that ranks them.

Here’s her step, with provisional holding the six teams in alphabetical order:

Language: Python
def standings(teams):
    return sorted(
        teams,
        key=lambda t: (
            t["points"],
            t["scored"] - t["conceded"],
        ),
        reverse=True,
    )

for t in standings(provisional):
    print(t["team"], t["points"])
  • Python compares two tuples field by field. Rovers and Athletic have the same points, so goal difference decides, and Rovers’ +9 beats Athletic’s +6. Dynamo and Wanderers are level on both, so their tuples are equal, and Python leaves them in the order the list had them: Dynamo stays third.
  • Ported a part at a time, the goal difference becomes a small function, goalDifference(), and the key turns into a compare function for toSorted(), handed two teams. JavaScript has no tuples to compare, so you write the “then” yourself with ||, JavaScript’s or operator.
  • Like Python’s or, || hands back its left side when that’s truthy, and otherwise its right side. For Dynamo and United, the points give 4, which is truthy, so that’s the answer. For Rovers and Athletic, they give 0, which is falsy in both languages, so || moves on to the goal difference. Dynamo and Wanderers give 0 for both, and 0 says the two are equal.
  • Last lesson, b minus a replaced the negated key, -t["points"]. Nothing in this key is negated: its direction is reverse=True. Keeping the direction out of the compare function too means sorting smallest first and calling .toReversed() on the sorted copy. That runs without an error, but it prints Wanderers third and Dynamo fourth, while Python keeps Dynamo third.
  • Before the reverse, Dynamo and Wanderers compare as 0, so they keep their list order. A sort that keeps equal items in their order is called stable. Python’s sort is stable, and JavaScript has guaranteed it since 2019. .toReversed() then turns the whole list round, the tied pair too.
  • Python’s reverse=True sorts largest first instead, and still keeps ties in list order. Python’s reversed() on the sorted list would swap them too.
  • So put the direction inside the compare function: for largest first, swap a and b, b minus a, for every field, and drop the reverse. Nothing turns the list round now, so the stable sort leaves Dynamo ahead of Wanderers, as reverse=True does.
  • Dynamo is above Wanderers only because the list arrived in alphabetical order. In last week’s order, with Wanderers ahead, the function would put Wanderers third, and so would Python’s line. A last tie-breaker that can’t tie, the team names compared with localeCompare(), keeps Dynamo third whatever order the records arrive in. In Python, you can sort twice, by name and then by the key, and two toSorted() calls work the same way.

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 By points alone, the provisional table has two pairs of teams level. Rovers and Athletic on sixteen, Dynamo and Wanderers on thirteen. You’ll port the line that ranks them.

00:13 Nadia’s standings() function holds it. The key is a tuple of the points, then goals scored minus conceded. reverse=True puts the largest first.

00:25 Python prints Rovers above Athletic, and Dynamo above Wanderers.

00:32 Python compares two tuples field by field. Rovers and Athletic have the same points, so it moves on to goal difference, and Rovers’ nine beats Athletic’s six.

00:43 Dynamo and Wanderers are level on both. Their tuples are equal, so Python leaves them in list order. The list is alphabetical, so Dynamo stays third.

00:56 Port it a part at a time: the goal difference becomes a small function. The key turns into a compare function for toSorted(), handed two teams.

01:07 Like the key, it sorts smallest first, a - b. JavaScript has no tuples to compare, so you write the “then” yourself: the points, then JavaScript’s or operator, ||, then the goal difference.

01:22 The print loop carries across as it is. Like Python’s or, the || operator hands back its left side when that’s truthy, and otherwise its right side.

01:35 For Dynamo and United, the points give four, which is truthy, so that’s the answer. For Rovers and Athletic, they give zero, which is falsy in both languages.

01:47 So the || operator moves on to goal difference. Dynamo and Wanderers give zero for both, and zero means the two are equal.

01:58 That leaves reverse=True. Last lesson, b - a replaced a negated key, minus the points. Nothing in this key is negated, so the port keeps the direction out too, and reverses the sorted copy with toReversed().

02:14 Python keeps Dynamo third. Which team does the port put third? Your turn: pause the video and predict.

02:27 Run it, and JavaScript prints Wanderers third and Dynamo fourth. Rovers are still above Athletic. Only the two teams level on everything have swapped, with no error.

02:42 Look at the sort before the reverse. Dynamo and Wanderers compare as zero, so they keep their list order. A sort that keeps equal items in order is called stable.

02:54 Python’s sort is stable, and JavaScript has guaranteed it since 2019. Then toReversed() turns the whole list round, the tied pair too. Python’s reverse=True sorts largest first, and still keeps ties in list order.

03:12 reversed() on the sorted list would swap them too.

03:17 So put the direction inside the compare function. For largest first, swap a and b in both fields. Then drop the reverse: the compare function now sets the direction.

03:30 Run again, and JavaScript prints Dynamo third and Wanderers fourth. All six rows match. Nothing turns the list round now, so the stable sort leaves Dynamo ahead of Wanderers, as reverse=True does.

03:48 Dynamo is above Wanderers only because the list arrived in alphabetical order. In last week’s order, the same function would put Wanderers third, and so would Python’s line.

04:00 So end with a tie-breaker that can’t tie: the team names, with localeCompare(). Dynamo moves back to third, whatever order the records arrive in.

04:12 In Python, you can sort twice, by name, then by the key, and two toSorted() calls work the same way.

04:20 The rule to keep: write the whole ranking in one compare function. Each field gets its direction, the || operator joins the fields, and the last one can’t tie.

04:32 Never reverse a sorted copy to get largest first. Next up: the exercise Rank the Top Scorers. You’ll rank the provisional scorers, most goals first, players level on goals by surname.

Become a Member to join the conversation.