Stable Sort By Multiple Keys

Sort records by several key selectors and directions with a guaranteed original-index tiebreak, so equal rows never swap positions.

JavascriptData Integrity

Code

javascriptsnippet
46 lines
function compareValues(left, right) {
  if (left === right || Object.is(left, right)) return 0;
  if (left === null || left === undefined) return 1;
  if (right === null || right === undefined) return -1;
  if (typeof left === "number" && typeof right === "number") {
    if (Number.isNaN(left)) return Number.isNaN(right) ? 0 : 1;
    if (Number.isNaN(right)) return -1;
    return left - right;
  }
  if (left instanceof Date && right instanceof Date) {
    return left.getTime() - right.getTime();
  }
  const leftText = String(left);
  const rightText = String(right);
  if (leftText === rightText) return 0;
  return leftText < rightText ? -1 : 1;
}

export function stableSortBy(items, selectors) {
  if (!Array.isArray(items)) throw new TypeError("items must be an array");
  if (!Array.isArray(selectors) || selectors.length === 0) {
    throw new TypeError("selectors must be a non-empty array");
  }
  const keys = selectors.map((entry) => {
    if (typeof entry === "function") return { select: entry, direction: "asc" };
    if (Array.isArray(entry) && typeof entry[0] === "function") {
      const direction = entry[1] ?? "asc";
      if (direction !== "asc" && direction !== "desc") {
        throw new RangeError("direction must be asc or desc");
      }
      return { select: entry[0], direction };
    }
    throw new TypeError("selector must be a function or [function, direction]");
  });

  return items
    .map((value, index) => ({ value, index }))
    .sort((left, right) => {
      for (const { select, direction } of keys) {
        const result = compareValues(select(left.value), select(right.value));
        if (result !== 0) return direction === "desc" ? -result : result;
      }
      return left.index - right.index;
    })
    .map((entry) => entry.value);
}

Inside the snippet

The working surface is the functions compareValues and stableSortBy — everything else is wiring.

Repetition is confined to for (const { select, direction } of keys) — the rest of the file is straight-line. Failure is loud: TypeError and RangeError aborts the current operation instead of degrading it.

The result comes back as an object carrying entry.

What to watch for

  • The guard left === null || left === undefined short-circuits the flow with an early return when its condition holds.

Putting it to use

Entry signature: export function stableSortBy(items, selectors)

stableSortBy is the public entry point; everything else in the file exists to support it.

The call returns entry.

Core lines

.sort((left, right) => {
  for (const { select, direction } of keys) {
    const result = compareValues(select(left.value), select(right.value));
    if (result !== 0) return direction === "desc" ? -result : result;
  }
  return left.index - right.index;
})
if (typeof entry === "function") return { select: entry, direction: "asc" };
throw new TypeError("selector must be a function or [function, direction]");

Interactive Tools for This Topic

FAQ

Does `stableSortBy` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
What happens on invalid input?
`TypeError` and `RangeError` is raised at the guard (`left === null || left === undefined`), so invalid state never reaches the main logic.
Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `compareValues`, `stableSortBy` at load time.