並び替え - Javascript

配列の並び替え

let num = [];
let min = 0;
let max = 29;

while(true){
    if(num.length == max + 1){
        break;
    }
    
    let r = Math.floor( Math.random() * (max + 1 - min) ) + min;
    if(num.includes(r) == false){
        num.push(r);
    }
}

function ascFunc(a, b) {
    return a - b;
}

function desFunc(a, b) {
    return b - a;
}

上記の配列 num を sort メソッドを使って並び替えると次のようになります。

console.log(num.sort());

// 実行結果
[
   0,  1, 10, 11, 12, 13, 14, 15, 16,
  17, 18, 19,  2, 20, 21, 22, 23, 24,
  25, 26, 27, 28, 29,  3,  4,  5,  6,
   7,  8,  9
]

昇順・降順に並べ替えるには次のようにします。

console.log(num.sort(ascFunc));
console.log(num.sort(desFunc));