Skip to main content
eLearner.app
Module 6 · Lesson 4 of 424/32 in the course~12 min
Module lessons (4/4)

sort

Sorting an array in JavaScript has a big trap: sort() mutates the original array and by default sorts as strings.

The trap

JS
const nums = [10, 2, 1, 20];
nums.sort();
// [1, 10, 2, 20]   ← !? sorted as strings: "1" < "10" < "2"

For numeric sorting you have to pass a comparator (a, b) => number:

  • a - b < 0 → a comes first
  • a - b > 0 → b comes first
  • a - b === 0 → order unchanged
JS
const nums = [10, 2, 1, 20];
nums.sort((a, b) => a - b);
// [1, 2, 10, 20]    ← ascending order

nums.sort((a, b) => b - a);
// [20, 10, 2, 1]    ← descending

Sorting objects by a field

JS
const utenti = [
  { nome: 'Anna', eta: 30 },
  { nome: 'Luca', eta: 12 },
  { nome: 'Sara', eta: 18 },
];

utenti.sort((a, b) => a.eta - b.eta);
// [{Luca,12}, {Sara,18}, {Anna,30}]

For strings you can compare them with localeCompare:

JS
const nomi = ['Bruno', 'aurora', 'Carlo'];
nomi.sort((a, b) => a.localeCompare(b));
// ['aurora', 'Bruno', 'Carlo']

Not mutating the original

Two options:

JS
// 1) copy + sort
const copia = [...nums].sort((a, b) => a - b);

// 2) toSorted (modern, ES2023)
const ordinati = nums.toSorted((a, b) => a - b);

Try it

Exercise#js.m6.l4.e1
Attempts: 0Loading…

Define `sortAscending(nums)`: return a NEW copy of the array, sorted in ascending order as numbers. The original must not change.

Loading editor…
Show hint

[...nums].sort((a, b) => a - b)

Solution available after 3 attempts

Review exercise

Exercise#js.m6.l4.e2
Attempts: 0Loading…

Define `sortByAgeAscending(people)`: given an array of { name, age }, return a new copy sorted by age ascending. The original must not change.

Loading editor…
Show hint

[...people].sort((a, b) => a.age - b.age)

Solution available after 3 attempts