Skip to content
GreenSnippets

Sort an array by multiple keys

Sort objects by one field, then break ties with another, with ascending or descending order per field.

JavaScript
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

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.