మాడ్యూల్ 6 · 4లో పాఠం 4కోర్సులో 24/32~12 min
మాడ్యూల్ పాఠాలు (4/4)
క్రమబద్ధీకరించు
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
వ్యాయామం#js.m6.l4.e1
ప్రయత్నాలు: 0లోడ్ అవుతోంది...
Define `sortAscending(nums)`: return a NEW copy of the array, sorted in ascending order as numbers. The original must not change.
ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు
[...nums].sort((a, b) => a - b)
3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది
Review exercise
వ్యాయామం#js.m6.l4.e2
ప్రయత్నాలు: 0లోడ్ అవుతోంది...
Define `sortByAgeAscending(people)`: given an array of { name, age }, return a new copy sorted by age ascending. The original must not change.
ఎడిటర్ లోడ్ అవుతోంది…
సూచనను చూపించు
[...people].sort((a, b) => a.age - b.age)
3 ప్రయత్నాల తర్వాత పరిష్కారం లభిస్తుంది