How to randomly shuffle elements in a JavaScript array?
In this post, we will learn how to randomly shuffle elements in a JavaScript array using various method in JavaScript.
Pure JavaScript
This shuffling method is implemented using Fisher-Yates algorithm which is by far very efficient shuffling algorithm.
function shuffle(arr) { var n = arr.length, tmp, index; while (n > 0) { index = Math.floor(Math.random() * n); n--; tmp = arr[n]; arr[n] = arr[index]; arr[index] = tmp; } return arr; } var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(shuffle(arr)); //[0, 8, 4, 9, 6, 7, 2, 5, 1, 3]
Array.prototype.sort() and Math.random
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; arr = arr.sort(() => Math.random() - 0.5); console.log(arr); // [8, 5, 1, 3, 4, 9, 2, 6, 7]