How do you numerically sort an array of integers in JavaScript without alphabetical bugs? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you numerically sort an array of integers in JavaScript without alphabetical bugs?

message-square
0

To numerically sort an array of integers in JavaScript without alphabetical bugs, pass a numeric comparator (a, b) => a - b for ascending order or (a, b) => b - a for descending order to Array.prototype.toSorted() (non-mutating) or Array.prototype.sort() (mutates in place). Calling .sort() without a comparator converts numbers to UTF-16 code-unit strings by default—causing [10, 2, 1] to sort as [1, 10, 2]—and using a - b (or < / > comparisons) avoids string coercion and prevents overflow or Infinity issues when comparing extreme values.


1. Ascending and Descending Numeric Sorting with toSorted() and sort()

Use toSorted((a, b) => a - b) when you want a new sorted array while keeping the original intact, or sort((a, b) => a - b) when sorting in place:

// Non-mutating ascending and descending sort for standard integers
function sortIntegers(values, order = "asc") {
  if (!Array.isArray(values)) {
    throw new TypeError("Expected values to be an array.");
  }

  const comparator =
    order === "desc" ? (a, b) => b - a : (a, b) => a - b;

  return values.toSorted(comparator);
}

// Example usage:
const scores = [100, 2, 25, -10, 8, 10];
console.log(sortIntegers(scores, "asc"));  // [-10, 2, 8, 10, 25, 100]
console.log(sortIntegers(scores, "desc")); // [100, 25, 10, 8, 2, -10]
console.log(scores);                       // [100, 2, 25, -10, 8, 10] (unchanged)
  • Why default .sort() fails: Without a comparator, 10 becomes "10" and 2 becomes "2", placing "10" before "2" alphabetically.
  • Prefer .toSorted() when immutability matters: It avoids accidental side effects on shared arrays in state or pipelines.

2. Safe Comparison for Extreme Numbers or BigInt

Subtraction (a - b) can return NaN if non-numbers slip in or Infinity / -Infinity for extreme values near ±Number.MAX_VALUE, while BigInt arrays require a BigInt comparator because a - b throws a TypeError on BigInt:

// Safe numeric comparator using relational comparisons and BigInt support
function compareNumbersAsc(a, b) {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
}

// Example usage with extreme numbers and BigInt:
const bigIds = [100000000000000000005n, 2n, 100000000000000000001n];
console.log(bigIds.toSorted(compareNumbersAsc)); // [2n, 100000000000000000001n, 100000000000000000005n]
  • Relational < / > avoids overflow: Returning -1, 1, or 0 works identically for standard number values and bigint values.
  • Check for NaN before sorting: NaN in an array can make sort order unpredictable unless filtered or validated first.

3. Preserving Original Order with Stable Sort

Modern JavaScript engines guarantee a stable sort, meaning elements that compare equal (0) keep their relative order—useful when sorting objects by an integer key while preserving tie order:

// Sort objects numerically by an integer property while preserving tie order
const tasks = [
  { id: 1, priority: 2 },
  { id: 2, priority: 1 },
  { id: 3, priority: 2 }
];

const byPriority = tasks.toSorted((a, b) => a.priority - b.priority);
console.log(byPriority); // id 2 (p:1), id 1 (p:2), id 3 (p:2)
  • Ties stay in original sequence: Items with equal priority (id: 1 before id: 3) remain in their input order.
  • Add a secondary tie-breaker when needed: Compare a second field (such as a.id - b.id) when equal primary keys should order deterministically by another attribute.