Skip to content

Instantly share code, notes, and snippets.

@mugyu
Created January 29, 2020 10:08
Show Gist options
  • Save mugyu/f82171e517b81735ae041c59f2d2e46c to your computer and use it in GitHub Desktop.
Save mugyu/f82171e517b81735ae041c59f2d2e46c to your computer and use it in GitHub Desktop.
JavaScrpt の Array に shuffle メソッドを実装 Fisher–Yates shuffle
Array.prototype.shuffle = function() {
var array = this;
for(var i = array.length - 1; i > 0; --i) {
// V8 の Math.random() のアルゴリズムは xorshift128+ らしい
var j = Math.floor(Math.random() * i);
var tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
return array;
}
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].shuffle());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment