Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- JavaScript
- GreenSnippets
- MIT
- Executed with Node.js 22
function sortBy(array, ...rules) {
// rule: [keyOrFn, "asc" | "desc"]
const compare = (a, b) => {
for (const [by, dir = "asc"] of rules) {
const get = typeof by === "function" ? by : (item) => item[by];
const x = get(a);
const y = get(b);
let result = 0;
if (typeof x === "string" && typeof y === "string") result = x.localeCompare(y);
else if (x < y) result = -1;
else if (x > y) result = 1;
if (result !== 0) return dir === "desc" ? -result : result;
}
return 0;
};
return [...array].sort(compare);
}Example / expected output
sortBy(people, ["lastName"], ["age", "desc"])How it works
Array.prototype.sort is stable and the comparator below returns the first non-zero result across the rules. Strings are compared with localeCompare so accents and case behave naturally. The input array is copied, not mutated.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.
- TypeScript Tested
Generic groupBy with key inference
Group an array into a Record by a property or function while keeping the item type.

