数字の配列を昇順に並び替える(ソートする).js
#JavaScript
あまりにも頻出すぎるのになぜかこのScrapboxにかかれていない、なぜ
Array.prototype.sort()を使えばすぐできます。
引数に関数を渡す必要があるので注意。
code:script.js
const array = 0, 3, 7, 2, 6, 9;
console.log(array.sort((a,b) => a - b)); // Expected Log Output : <Number[]> 0, 2, 3, 6, 7, 9
console.log(array); // Expected Log Output : <Number[]> 0, 2, 3, 6, 7, 9
元の配列を変更したくなければArray.prototype.toSorted()を使う。配列の非破壊的変更
ただしこのメソッドはBaseline 2023なのでちょっと古い環境だと使えない
code:script.js
const array = 0, 3, 7, 2, 6, 9;
console.log(array.toSorted((a,b) => a - b)); // Expected Log Output : <Number[]> 0, 2, 3, 6, 7, 9
console.log(array); // Expected Log Output : <Number[]> 0, 3, 7, 2, 6, 9
古い環境でやりたいなら配列をクローン.jsも参照。
Author : 綾坂こと