配列を破壊的にソートする。比較関数で順序を制御
// ── 注意: sort() は元の配列を変更する(破壊的)─────────
const nums = [3, 1, 4, 1, 5, 9, 2];
const sorted = [...nums].sort((a, b) => a - b); // スプレッドでコピー
console.log(sorted); // [1, 1, 2, 3, 4, 5, 9]
console.log(nums); // [3, 1, 4, 1, 5, 9, 2](元は変わらない)
// ── 文字列のソート ──────────────────────────────────────
const words = ['banana', 'apple', 'cherry'];
words.sort(); // デフォルトは文字コード順
console.log(words); // ['apple', 'banana', 'cherry']
// ── オブジェクト配列のソート ────────────────────────────
const users = [
{ name: '田中', age: 30 },
{ name: '鈴木', age: 20 },
{ name: '佐藤', age: 25 },
];
// 年齢順(昇順): a - b が正なら b が前に来る
const byAge = [...users].sort((a, b) => a.age - b.age);
// [鈴木(20), 佐藤(25), 田中(30)]
// ── 降順にする場合 ───────────────────────────────────
const byAgeDesc = [...users].sort((a, b) => b.age - a.age);引数なしだとUnicode順になるため数値ソートには必ず比較関数を渡す。ES2023のtoSorted()は非破壊版。