配列の順番をシャッフルする自作関数【JavaScript】

  1. やりたいこと
  2. 方法
  3. 原理
  4. 補足

やりたいこと

配列の要素の順番だけ、無作為に並び替えたい。

var nums = [0,1,2,3,4,5,6];

このような配列を

nums = [3,1,2,6,5,4,0];

こんな感じにしたい。

方法

function shuffle(nums){
    var mirror = [];
    
    mirror.push(...nums.splice([Math.floor(Math.random()*7)],1));
    mirror.push(...nums.splice([Math.floor(Math.random()*6)],1));
    mirror.push(...nums.splice([Math.floor(Math.random()*5)],1));
    mirror.push(...nums.splice([Math.floor(Math.random()*4)],1));
    mirror.push(...nums.splice([Math.floor(Math.random()*3)],1));
    mirror.push(...nums.splice([Math.floor(Math.random()*2)],1));
    mirror.push(...nums.splice([Math.floor(Math.random()*1)],1));
    
    return mirror;
}


var nums = [0,1,2,3,4,5,6];
nums = shuffle(nums);

for文を使うと、

function shuffle(nums){
    var mirror = [];
    
    for(var i=nums.length; i>0; i--){
        mirror.push(...nums.splice([Math.floor(Math.random()*i)],1));
    }
    
    return mirror;
}


var nums = [0,1,2,3,4,5,6];
nums = shuffle(nums);

原理

仮の配列(mirror)を用意して、要素をひとつずつ移動させているのだが、
ランダムな並びに変えるために、

numsの何番目の要素を引き抜くかを乱数で決めている。

numsは適宜置き換えてください。

補足

は配列を中身の並びに変換する関数?かなにか。

…[0,1,2]
 ↓
0,1,2

splice は、引数を2つとり、
配列のa番目の要素から、b個の要素を取り除く関数。
言い換えると、a番目から、(a+b-1)番目の要素を取り除く。
返り値が、削除された要素からなる配列。

最近の記事