liveBook · Manning

Array.prototype.sort

As explained in Secrets of the JavaScript Ninja, Third Edition

A JavaScript method that sorts an array in place using a default ordering or a supplied comparison function.

Need to put an array in order? Array.prototype.sort rearranges its items in place. Unlike map or filter, it does not create a new array for the result. Supply a comparison callback when the order should follow a rule you choose. section 10.1.4 section 10.5

The comparison callback receives two items, a and b. Its return value tells sort how to order them:

Sort numbers

const values = [0, 3, 2, 5, 7, 4, 8, 1]; values.sort((a, b) => a - b); Subtracting the two numbers supplies the negative, positive, or zero result the comparison callback needs. The array itself is reordered. section 5.2.2 section 10.5

For names or other strings, avoid assuming that character-code comparisons produce the order users expect across Unicode. Intl.Collator provides a locale-tailored compare method that fits directly into a sort callback. The JavaScript engine chooses the sorting algorithm; the callback specifies the ordering, not the algorithm. section 10.1.4

Listing 10.9 Sorting an array
const ninjas = [
  { name: "Yoshi" },
  { name: "Yagyu" },
  { name: "Kuma" },
];
 
const collator = new Intl.Collator();  #A
 
ninjas.sort((ninja1, ninja2) =>  #B
  collator.compare(ninja1.name, ninja2.name),  #B
);  #B

console.assert(
  ninjas[0].name === "Kuma" &&
    ninjas[1].name === "Yagyu" &&
    ninjas[2].name === "Yoshi",
  "The ninjas are now in alphabetical order",
);

A complete example sorts objects by their name properties with Intl.Collator and checks the resulting order. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains all three comparison results and defers the choice of sorting algorithm to the JavaScript engine.
Examples
Uses numeric subtraction to sort numbers and Intl.Collator to sort objects by name.
What it assumes
Assumes familiarity with arrays and function arguments while explaining the comparison callback's return-value rule.
What you can do after
Operate/configure it with numeric or Intl.Collator comparison callbacks to order an existing array.
How it connects
Connects sorting to callbacks, array mutation, and locale-aware string comparison with Intl.Collator.

Related concepts

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