Sorting Numbers With a Compare Function
In this lesson, you sorted how many times the pager went off in each of the last eight weeks, in JavaScript, and found out why the default sort puts 11 before 2.
- The first port of Python’s
sorted(pages),pages.toSorted(), the same as for the wiki list, gives the wrong order for numbers. The working port ispages.toSorted((a, b) => a - b), explained below. - With no argument,
toSorted()andsort()compare these numbers by their text, character by character, though the sorted array still holds numbers. That worked for the wiki’s names and is wrong for numbers:"11"and"14"both come before"2", because their first character,"1", comes before"2". - Sorted as strings in Python, these numbers come out in the same order:
sorted(["3", "9", "0", "14", "2", "7", "4", "11"])gives['0', '11', '14', '2', '3', '4', '7', '9']. But Python’ssorted()compares the numbers themselves, and JavaScript’s default compares their text instead. - To sort counts like these as numbers, pass a compare function,
(a, b) => a - b. It’s an arrow function: the parametersaandb, the arrow, then the value it returns. It has the shape of Python’slambda a, b: a - b, but Python’ssorted()takes no function that compares two items: it compares the numbers itself. toSorted()calls the function with two items at a time and reads the sign of the result: negative putsafirst, positive putsbfirst, and zero keeps their order. For 2 and 11,2 - 11is-9, so 2 goes first. Wheneverais the smaller number,a - bis negative.- For largest first, swap the subtraction to
(a, b) => b - a. For 2 and 11,11 - 2is9, positive, sobgoes first, and 11 comes before 2. Watch out: JavaScript has no keyword arguments, so it readsreverse=trueas assigning to an undeclared variable,reverse, and stops withReferenceError: reverse is not defined. pages.sort((a, b) => a - b)reorderspagesitself, andtoSorted(), like Python’ssorted(), leaves it alone. Never sort numbers without a compare function.
Here’s the Python step:
pages = [3, 9, 0, 14, 2, 7, 4, 11]
print(sorted(pages))
print(sorted(pages, reverse=True))