JS Built-ins
← Array181 / 226
ArrayArray.prototype.sortadvanced

Array.prototype.sort() β€” stable sort by last name

πŸ“– Usage Example
const items = [{rank:1,name:'A'},{rank:2,name:'B'},{rank:1,name:'C'}]
items.sort((a, b) => a.rank - b.rank)
// A and C remain in original order (stable sort)

Modern JS engines guarantee a stable sort β€” elements with equal keys preserve their original order.

Array.prototype.sort() β€” multi-key stable sort

Modern JavaScript engines guarantee a stable sort. When two elements are equal on the primary key, their relative order is preserved. You can make this explicit with a secondary comparator.

Challenge: Implement sortByLastName(people) that sorts by last name ascending, using first name as a tiebreaker.

sortByLastName([
  {first:'Bob',  last:'Smith'},
  {first:'Alice',last:'Jones'},
  {first:'Anna', last:'Jones'},
])
// β†’ [{first:'Alice',last:'Jones'},{first:'Anna',last:'Jones'},{first:'Bob',last:'Smith'}]
πŸ’‘ Hints (2)
  • β€’ `localeCompare` returns a negative, zero, or positive number β€” exactly what `sort` expects.
  • β€’ Only fall through to the secondary comparator when `lastCmp === 0`.