JavaScript shuffle array (randomize)

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