K
K
Konstantin2021-07-04 23:12:21
JavaScript
Konstantin, 2021-07-04 23:12:21

How to generate an array of only unique numbers of a certain length?

I need to generate an array of unique numbers.
The length of the array (unikArr) should be, for example, equal to lengthArr
How to specify in the loop condition, work until the array is filled to the required lengthArr value

let generateUnikArr = (lengthArr) => {
                    //указываю диапазон чисел которые мне необходимы в массиве
                    let min = 1
                    let max = 100
                    let unikArr = []
                    let i = 0
                 
                    while( i < ???) {
                        //генерирую число
                        let randomNum = Math.floor(Math.random() * ((max + 1) - min)) + min 
                        //проверяю есть ли число в уже массиве
                        let dublicate = wins.includes(randomNum)
                        if( dublicate == true ) {
                            //если есть ничего не делаю
                        } else {
                            //если нет такого числа в массиве, то добавляю
                            wins.push(randomNum) 
                        }
                        i++
                    }

                    return unikArr 
                }
                console.log(randomWin(3))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-07-04
@gradk

function createRandomArr(length, min, max) {
  const values = Array.from({ length: max - min + 1 }, (n, i) => min + i);
  return Array.from({ length }, () => values.splice(Math.random() * values.length | 0, 1)[0]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question