</>
Skip to content
JavaScript lessons (24/64)

JavaScript — Array Sort

The default sort will betray you

sort() converts items to strings and compares alphabetically:

[1, 10, 2, 21].sort();        // [1, 10, 2, 21] 😱 — "10" < "2" as strings!
["banana", "Apple"].sort();   // ["Apple", "banana"] — uppercase first

Numeric sorting requires a compare function:

[1, 10, 2, 21].sort((a, b) => a - b);   // [1, 2, 10, 21] ascending
[1, 10, 2, 21].sort((a, b) => b - a);   // descending

How the comparator works

The function receives two items; its return value decides order:

return < 0  →  a before b
return > 0  →  b before a
return 0    →  keep relative order

(a, b) => a - b is just a compact "ascending by number."

It mutates — copy first

const scores = [70, 95, 60];
const sorted = [...scores].sort((a, b) => b - a);
// scores untouched; sorted holds [95, 70, 60]

Modern non-mutating alternative: toSorted((a,b) => …).

Sorting objects

By any key:

const users = [
    { name: "Ada",   age: 36 },
    { name: "Bo",    age: 22 },
    { name: "Cleo",  age: 45 },
];

users.sort((a, b) => a.age - b.age);            // youngest first
users.sort((a, b) => a.name.localeCompare(b.name)); // alphabetical ✓

localeCompare handles case/accented characters properly — never < on names.

Multi-key sorts

data.sort((a, b) =>
    b.score - a.score ||                 // score desc,
    a.name.localeCompare(b.name)         // then name asc
);

|| chains: first nonzero result wins.

Strings with numbers inside

["v10", "v9", "v2"].sort();                    // ["v10","v2","v9"] wrong
["v10", "v9", "v2"].sort((a,b) =>
    parseInt(a.slice(1)) - parseInt(b.slice(1))); // v2 v9 v10 ✓

// or modern locale options:
arr.sort((a,b) => a.localeCompare(b, undefined, { numeric: true }));

Case-insensitive & locale-aware

names.sort((a, b) =>
    a.toLowerCase().localeCompare(b.toLowerCase()));

// Swedish/German etc. correct ordering:
words.sort(new Intl.Collator("de").compare);

Reverse tricks

nums.sort((a,b) => a - b).reverse();   // fine but double work
nums.sort((a,b) => b - a);             // direct descending ✓

Quick reference

GoalComparator
Numbers ↑(a,b)=>a-b
Numbers ↓(a,b)=>b-a
Strings A→ZlocaleCompare
Object by key(a,b)=>a.key-b.key or localeCompare
Multi-keyfirst || second

Common mistakes: default-sorting numbers; forgetting mutation; string < on user-facing text.

Mini Practice

  1. Fix [80, 9, 700] default-sort disaster; explain in a comment why it happened
  2. Sort products price-ascending; tie-break alphabetically
  3. Non-mutating sort of your playlist (spread + toSorted both)
  4. Version-string sort: v1.2, v1.10, v1.2.5 → numeric-aware order
  5. Locale-sort German words with umlauts via Intl.Collator

Next: array iteration →

Related Topics

Frequently Asked Questions about Array Sort

What is Array Sort in JavaScript?

Array Sort is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Array Sort?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Array Sort.

Why is Array Sort important in JavaScript?

Array Sort is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.