LoginSignup
2
1

More than 3 years have passed since last update.

[JavaScript] 配列の要素をシャッフルする実装方法

Last updated at Posted at 2021-03-30

はじめに

JavaScriptの配列の要素を呼び出すたびに要素数を変えずに
ランダムな順番の配列を生成する関数を生成したので備忘録として残しておく

あまりネットに記事がなかったので、役に立てばと思って書きました!

配列の要素をシャッフルする実装方法 ①

for文を用いて実装する方法

/**
 * 配列の要素の値を変更せずに要素の順番を並べ替える関数
 * (e.g) [0,1,2,3,4] => [1,3,2,0,4]
 */
 const shuffleArray = (array) => {
    const cloneArray = [...array]

    for (let i = cloneArray.length - 1; i >= 0; i--) {
      let rand = Math.floor(Math.random() * (i + 1))
      // 配列の要素の順番を入れ替える
      let tmpStorage = cloneArray[i]
      cloneArray[i] = cloneArray[rand]
      cloneArray[rand] = tmpStorage
    }

    return cloneArray
  }

// 要素が数値の配列でもいける
console.log(shuffleArray([0,1,2,3,4]));
// expected output : [0,3,4,1,2]

// 要素が文字列の配列でもいける
console.log(shuffleArray(['JavaScript','React','Vue']));
// expected output : ['React','JavaScript','Vue']

// 要素がオブジェクトの配列でもいける
console.log(shuffleArray([{id:1,age:23},{id:2,age:24},{id:3,age:25}]));
// expected output : [{id:2,age:24},{id:1,age:23},{id:3,age:25}]

配列の要素をシャッフルする実装方法 ②

reduce関数を用いて実装する方法

// reduceを用いた実装方法
const shuffleArray = (array) => {
  const cloneArray = [...array];

  const result = cloneArray.reduce((_,cur,idx) => {
    let rand = Math.floor(Math.random() * (idx + 1));
    cloneArray[idx] = cloneArray[rand]
    cloneArray[rand] = cur;
    return cloneArray
  })

  return result;
}

console.log(shuffleArray([1,2,3,4,5]))
// expected output : [3,2,5,1,4]

簡単に解説

  • Math.floor()
    実引数に与えられた数値以下の「整数」を返す
    (例) Math.floor(5.95) → 出力結果 : 5

  • Math.random()
    0以上1未満の「乱数」を返す
    (例) Math.random() → 出力結果 : 0.39750053425848453

リロードするたびにリストの順番を
ランダムに入れ替えたい時なんかに使えます!

他にもこんな良い実装方法があるとか
知見のある強い人がいたらコメントいただけると嬉しいです!

参考文献

Math.floor | MDN
Math.random | MDN

2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1