orderByLoading saved progress…

orderBy

orderBy sorts a collection of objects by multiple keys, each ascending or descending independently — "by age, then by name," or "by priority descending, then by date ascending." It's Array.prototype.sort with the fiddly comparator written for you, including stability and per-key direction.

Implement orderBy(collection, keys, orders). keys is a list of property names (or accessor functions); orders[i] is 'asc' or 'desc' for keys[i]. Compare by the first key, break ties with the next, and so on. Keep it stable and return a new array.

Signature

function orderBy(collection, keys, orders) {
  // keys: (string | (item) => value)[]
  // orders: ('asc' | 'desc')[]  — defaults to 'asc' per key
}

Examples

const people = [
  { name: 'Ann', age: 30 }, { name: 'Bob', age: 25 },
  { name: 'Cat', age: 30 }, { name: 'Dan', age: 25 },
];
orderBy(people, ['age', 'name'], ['asc', 'asc']).map((p) => p.name);
// ['Bob', 'Dan', 'Ann', 'Cat']  — by age, ties broken by name
orderBy(people, ['age', 'name'], ['asc', 'desc']).map((p) => p.name);
// ['Dan', 'Bob', 'Cat', 'Ann']  — age ascending, name descending

Notes

  • Multiple keys — compare by keys[0]; only when those are equal do you compare by keys[1], and so on.
  • Per-key directionorders[i] flips just that key. Missing entries default to 'asc'.
  • Keys can be functions — an accessor like (item) => item.length is a valid key.
  • Stable — elements equal on every key keep their original relative order.
  • New array, no mutation — return a sorted copy; leave the input array unchanged.
Loading editor…