简体   繁体   中英

How to generate an array with not repeating numbers in ES6?

I'm trying to generate an array of random numbers in ES6 - numbers should not be repeated.

Currently, my function generates an array of random numbers, but they are repeating:

winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53));

Here is non-ES6 solution that I've found: Non-ES6 solution

This solution with Set is not running in a for-loop:

for (let i = 1; i <= draws; i += 1) {
      // Generating a random array of 6 number

      const winArray = new Set();
      while (winArray.size < 6) winArray.add(Math.floor(Math.random() * 53));
}

You could take a Set and fill this set until the wanted size.

 var numbers = new Set; while (numbers.size < 6) numbers.add(Math.floor(Math.random() * 53)); console.log(...numbers); 

For getting more numbser sets, you could take an empty set for each draw.

 var numbers, draws = 5, i; for (i = 0; i < draws; i++) { numbers = new Set; while (numbers.size < 6) numbers.add(Math.floor(Math.random() * 53)); console.log(...numbers); } 

A Set will only allow unique properties (no duplicates).

 let winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53)); winArray = [...new Set(winArray)] console.log(winArray) 

Here's a solution that shuffles a list of unique numbers (no repeats, ever).

for (var a=[],i=0;i<100;++i) a[i]=i;

function shuffle(array) {
  var tmp, current, top = array.length;
  if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
  }
  return array;
}

a = shuffle(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM