Array Sort and Reverse in JavaScript

Introduction

Sorting and reversing change presentation order for users—leaderboards, price lists, and timelines. JavaScript’s sort mutates the array and compares values as strings by default. This chapter shows safe numeric sorts, custom comparators, and toSorted (non-mutating) in modern environments.

Prerequisites

reverse — Flip Order

javascript
// reverse mutates
const queue = [1, 2, 3];
queue.reverse();
console.log(queue);

Default sort — Lexicographic (String) Order

javascript
// String sort surprise with numbers
const nums = [10, 2, 30, 21];
nums.sort();
console.log(nums);

"10" comes before "2" as strings. For numbers, pass a comparator.

Numeric Sort with Comparator

javascript
// Ascending numbers
const values = [10, 2, 30, 21];
values.sort((a, b) => a - b);
console.log(values);
 
// Descending
values.sort((a, b) => b - a);
console.log(values);

Comparator rules:

  • negative → a before b
  • positive → b before a
  • zero → equal order (stable in modern engines)

Sorting Objects

javascript
// Sort users by name
const users = [
  { name: "Sam", score: 88 },
  { name: "Ada", score: 92 },
  { name: "Lin", score: 75 },
];
 
users.sort((a, b) => a.name.localeCompare(b.name));
console.log(users);

Non-Mutating toSorted (ES2023+)

javascript
// toSorted returns new array
const original = [3, 1, 2];
const sorted = original.toSorted((a, b) => a - b);
 
console.log(original);
console.log(sorted);

If toSorted is unavailable, use const sorted = [...original].sort(...).

Copy Before Sort When Needed

javascript
// Spread then sort to keep source order
const source = [5, 1, 4];
const ordered = [...source].sort((a, b) => a - b);
console.log(source, ordered);

Mini Example: Ranking Game Scores

javascript
// Sort scores descending for leaderboard
const scores = [72, 95, 88, 95, 60];
 
const leaderboard = [...scores]
  .sort((a, b) => b - a)
  .map((score, index) => `#${index + 1}: ${score}`);
 
leaderboard.forEach((line) => console.log(line));

FAQ

Is sort stable?

Modern JavaScript requires stable sort—equal elements keep relative order.

Can I sort without a comparator for strings?

Default sort() works for string arrays—still mutates the array.

How do I sort dates?

Compare numeric timestamps: (a, b) => a.time - b.time after parsing to Date.

What comes next?

Map, filter, reduce.