lundi 19 mars 2018

How to make `shuffle` with less code

What is a clean way of creating an array of shuffled values, without replacement from an array in javascript.
That's my code to achieve shuffle, but the code is graceless, I want to get a better solution.

const shuffle = nums => {
  const res = []
  const foo = nums.slice(0)
  let i = foo.length - 1
  while (i-- >= 0) {
    res.push(foo.splice(Math.round(Math.random() * i), 1)[0])
  }
  return res
}




Aucun commentaire:

Enregistrer un commentaire