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:
- A negative number if `a` should come before `b`. section 10.1.4
- A positive number if `a` should come after `b`. section 10.1.4
- Zero if they are equivalent for sorting purposes. section 10.1.4
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



