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:
- Negative: put a before b. section 10.1.4
- Positive: put a after b. section 10.1.4
- Zero: treat a and b as equivalent for sorting. section 10.1.4
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
