liveBook · Manning

Comparison function

As explained in Secrets of the JavaScript Ninja, Third Edition

A compare function is a sorting callback that returns a negative, positive, or zero number to order two items.

Need an array in a particular order? Pass a comparison function to JavaScript’s `sort` method. The function receives two items and decides which comes first; the sorting algorithm remains the JavaScript engine’s job. section 5.2.2 section 10.1.4

For items `a` and `b`, return:

Sort numbers in ascending order

`const values = [0, 3, 2, 5, 7, 4, 8, 1]; values.sort((a, b) => a - b);` Subtraction gives the required negative, positive, or zero result without implementing a sorting algorithm. section 5.2.2

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",
);

For names, create an `Intl.Collator` and pass a callback that compares each pair of names. Character-code comparisons with `<` can be a poor fit for Unicode text; a collator is tailored to the user’s locale. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines the three return-value cases and works through numeric and string sorting, leaving the sorting algorithm to the JavaScript engine.
Examples
Uses subtraction to order numbers and `Intl.Collator.compare` to order names.
What it assumes
Assumes familiarity with arrays and functions while explaining how a sorting callback receives items and returns an ordering result.
What you can do after
Apply it via `Array.prototype.sort` to specify numeric or locale-aware name ordering without implementing a sorting algorithm.
How it connects
Connects array sorting with callbacks, first-class functions, and locale-aware string comparison.

Also explained in

Compare how 4 books explain comparison function →

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.