JSFiddle - React, Tailwind, and code Playground

by lchau

JavaScript

var list = [1, 2, 3, 4, 5, 6, 7, 8];
function shuffle(array) {
  if (!Array.isArray(array) || array.length < 2) {
    return array;
  }
  
  
  /* var length = array.length,
      tmp,
      index;
  while (length) {
    index = Math.floor(Math.random() * length--);
    tmp = array[length];
    array[length] = array[index];
    array[index] = tmp;
  
  } */
  
  var index = -1;
  array.forEach(function(value) {
    var random = Math.floor(Math.random() * ++index);
    array[index] = array[random];
    array[random] = value;
  });
  return array; 
}

shuffle(list);
console.log(list);