Mô-đun 6 · Bài học 4 trong tổng số 424/32 trong khóa học~12 min
Bài học theo mô-đun (4/4)
sắp xếp
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 →acomes firsta - b> 0 →bcomes firsta - 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] ← descendingSorting 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
tập thể dục#js.m6.l4.e1
Nỗ lực: 0Đang tải…
Define `sortAscending(nums)`: return a NEW copy of the array, sorted in ascending order as numbers. The original must not change.
Đang tải trình chỉnh sửa…
Hiển thị gợi ý
[...nums].sort((a, b) => a - b)
Giải pháp khả dụng sau 3 lần thử
Review exercise
tập thể dục#js.m6.l4.e2
Nỗ lực: 0Đang tải…
Define `sortByAgeAscending(people)`: given an array of { name, age }, return a new copy sorted by age ascending. The original must not change.
Đang tải trình chỉnh sửa…
Hiển thị gợi ý
[...people].sort((a, b) => a.age - b.age)
Giải pháp khả dụng sau 3 lần thử