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

















