モジュール 6 · レッスン 4 / 4コース内の 24/32~12 min
モジュールのレッスン (4/4)
並べ替える
JavaScript での配列の並べ替えには大きな罠があります: sort() 元の配列を変更します
デフォルトでは文字列としてソートされます。
罠
JS
const nums = [10, 2, 1, 20];
nums.sort();
// [1, 10, 2, 20] ← !? sorted as strings: "1" < "10" < "2"数値並べ替えの場合、コンパレータ (a, b) => number を渡す必要があります。
a - b< 0 →aが最初に来るa - b> 0 →bが最初に来るa - b=== 0 → 順序は変更されません
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フィールドによるオブジェクトの並べ替え
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}]文字列の場合は、localeCompare と比較できます。
JS
const nomi = ['Bruno', 'aurora', 'Carlo'];
nomi.sort((a, b) => a.localeCompare(b));
// ['aurora', 'Bruno', 'Carlo']オリジナルを改変しない
2 つのオプション:
JS
// 1) copy + sort
const copia = [...nums].sort((a, b) => a - b);
// 2) toSorted (modern, ES2023)
const ordinati = nums.toSorted((a, b) => a - b);試してみてください
運動#js.m6.l4.e1
試行回数: 0読み込み中…
`sortAscending(nums)` を定義します。数値として昇順にソートされた配列の新しいコピーを返します。オリジナルは変更してはいけません。
エディターを読み込み中…
ヒントを表示
[...nums].sort((a, b) => a - b)
3 回の試行後に解決策が利用可能になります
復習演習
運動#js.m6.l4.e2
試行回数: 0読み込み中…
`sortByAgeAscending(people)` を定義します。 { name, age } の配列を指定すると、年齢の昇順でソートされた新しいコピーを返します。オリジナルは変更してはいけません。
エディターを読み込み中…
ヒントを表示
[...人].sort((a, b) => a.age - b.age)
3 回の試行後に解決策が利用可能になります