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.
function orderBy(collection, keys, orders) {
// keys: (string | (item) => value)[]
// orders: ('asc' | 'desc')[] — defaults to 'asc' per key
}
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
keys[0]; only when those are equal do you compare by keys[1], and so on.orders[i] flips just that key. Missing entries default to 'asc'.(item) => item.length is a valid key.