0
export default function App() {


  Array.prototype.shuffle = function () {
    let rnum=[]
    let random = this
    for (let i= 0; i < random.length; i++){
      let randomizer = Math.floor(Math.random()*(this.length));


      rnum.push(randomizer)
     
    }
    console.log(rnum)
    
    
  }
  let random = [0,1,2,3,4].shuffle()

This is my current code. It currently prints a random array of the "random" numbers, how ever im trying to print all the available numbers without any one number repeating itself inside of the "rnum" array. If anyone could help me out id be gratefull!

Lineu Pastorelli
  • 502
  • 1
  • 8
  • 20
  • You have numbers in an array and you want to replace them with random numbers that must be unique? – Samuel Goldenbaum Oct 04 '21 at 18:00
  • Does this answer your question? [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – Samuel Goldenbaum Oct 04 '21 at 18:06
  • What i want to do is shuffle the numbers currently inside the 'random' array, not replace them. Youre suggested solution didnt really work in react native, atleast not when i tried! Il keep trying and will uptade if i find a solution – Sebastian Pehrson Oct 05 '21 at 13:32

1 Answers1

0
  let index= this.length, randomIndex

  while(index != 0) {
    randomIndex = Math.floor(Math.random()*index)
    index--

    [this[index], this[randomIndex]] = [this[randomIndex], this[index]]
  }
  return this
  
  
}
var random = [0,1,2,3,4].shuffle()
  console.log(random) 

I solved the problem by using Samuel Goldenbaum's suggestion to look at a previous solution in JS "How to randomize (shuffle) a JavaScript array?". I simply had tu replace all replace "array" with "this"!