JavaScript shuffle array (randomize)
Learn how to randomize any JavaScript array with this simple function. It shuffles the array in place without creating a copy. Try the interactive example to see it in action and easily integrate it into your projects!
Fast, easy and simple function that randomizes any JavaScript array.
Copy the code below to one of your existing project. Keep in mind that this function will return the same array as it is given after the array have been shuffled, it will not create a copy.
function shuffleArray (arr) {
for (let i = arr.length - 1; i > 0; i--) {
const r = Math.floor(Math.random() * (i + 1));
[arr[i], arr[r]] = [arr[r], arr[i]];
}
return arr;
};
See it in action
See the Pen JavaScript Shuffle Array by codegravy (@rasmus-puls) on CodePen.
Click the shuffle button to randomize the array. Click the restore button to return to initial array order.
Codepen.io link: https://codepen.io/rasmus-puls/pen/VwLmJew