2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【javascript】配列のシャッフル

Last updated at Posted at 2021-04-03

コード

Math.random() - 0.5と大差ないっぽい

const shuffleArray = arr => arr.sort(() => Math.random() - Math.random());

console.log( shuffleArray([...Array(5).keys()]) );

参考にした記事

[JavaScript] 配列の要素をシャッフルする実装方法
https://qiita.com/k_kazukiiiiii/items/7da39df4fe28d2fb3898
この記事を書くきっかけになった記事です。

javascriptでワンライナーでArray shuffle (2016年版)
https://qiita.com/terrierscript/items/94bf137c12bcda9e5dab
sortでいけるって教えてくれた記事。

Array#sort実装のshuffleは偏る
https://qiita.com/minodisk/items/94b6287468d0e165f6d9
sort微妙って教えてくれた記事。

入力配列をシャッフルした配列を返す関数
https://qiita.com/fushikky/items/9ba4ed092133d47b8822
コメントの@iMasanariさんのコードが良さそうなので単純化しました。

感想

Fisher-Yatesが最適解なんだろうけど、このコード量は魅力的。

2
3
4

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?