liveBook · Manning

Sorting algorithm

As explained in Secrets of the JavaScript Ninja, Second Edition

An Array method that sorts an array in place using a comparison function or default ordering.

Sorting puts array items in order. Writing a sorting algorithm yourself means choosing an approach, implementing it, and watching for subtle bugs. JavaScript arrays provide sort() instead: the engine handles the rearrangement, while you supply a comparison function that defines the order. section 9.1.4

For each pair of items, the comparison function returns:

  • A value below zero when the first item should come before the second. section 9.1.4
  • Zero when the items are equal for sorting purposes. section 9.1.4
  • A value above zero when the first item should come after the second. section 9.1.4

Choose what to compare

For numbers in ascending order, use array.sort((a, b) => a - b). For objects, compare the property you care about; sorting by name can place Kuma before Yagyu before Yoshi. The array being sorted reflects the result. section 9.1.4

Listing 9.11. Sorting an array
const ninjas = [{name: "Yoshi"}, {name: "Yagyu"}, {name: "Kuma"}];

ninjas.sort(function(ninja1, ninja2){                       #A
  if(ninja1.name < ninja2.name) { return -1; }              #A
  if(ninja1.name > ninja2.name) { return 1; }               #A
                                                            #A
  return 0;                                                 #A
});                                                         #A

assert(ninjas[0].name === "Kuma", "Kuma is first");
assert(ninjas[1].name === "Yagyu", "Yagyu is second");
assert(ninjas[2].name === "Yoshi", "Yoshi is third");

A complete sort() call compares object names and checks the resulting array order. section 9.1.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains comparator return values and works through object sorting, but leaves the engine’s sorting algorithm behind the scenes.
Examples
Shows numeric subtraction as a comparator and sorts objects alphabetically by name with assertions checking their order.
What it assumes
Assumes familiarity with arrays and callbacks while explaining what comparator return values mean.
What you can do after
Apply it via Array.sort() by writing a comparator for the desired item order.
How it connects
Connects sorting to JavaScript arrays, callbacks, and array methods.

Also explained in

Compare how 18 books explain sorting algorithm →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.