How can I make a random array with no repeats?

前端 未结 6 1886
星月不相逢
星月不相逢 2020-12-20 04:13

I\'ve been searching around for some answers to this issue, but nothing seems to work when I try to find a solution.

What I\'m trying to achieve is to make a spinner

6条回答
  •  生来不讨喜
    2020-12-20 04:42

    Another approach you could take given the fact that you already have the array values and you need to randomize their position is to generate a unique random values with Set:

    var data = ['360', '330', '300', '270', '240', '210','180', '150', '120', '90', '60', '30'];
    
    let getUniqueRandomNumbers = n => {
      let set = new Set()
      while (set.size < n) set.add(Math.floor(Math.random() * n))
      return Array.from(set)
    }
    
    let result = getUniqueRandomNumbers(data.length).map(x => data[x])
    
    console.log(result)

    The idea is to generate the indexes of the new array and then using those to populate it via Array.map.

    Another approach you could take is via Array.sort and Math.random:

    var data = ['360', '330', '300', '270', '240', '210','180', '150', '120', '90', '60', '30'];
    
    let result = data.sort(function(a, b){
     return 0.5 - Math.random()  // <— sort needs a number and this makes it work
    });
    
    console.log(result);

提交回复
热议问题