There is an array with 54 cards with random numbers. I get 9 values, but periodically they are repeated, looking for topics to exclude duplicate numbers, but in this case it leaves an empty value in the array and does not fill it with a new number.

//3апись 9 id в массив randId var randId = new Array(9); for (var i = 0; i < randId.length; i++) { // В таблице 9 строк var rand = Math.floor(Math.random() * cards.length); if (randId.indexOf(rand) === -1) { // проверим есть оно у нас или нет randId[i] = rand; } } 

    3 answers 3

     const cards = ['♠A', '♠2', '♠3', '♠4', '♠5', '♠6', '♠7', '♠8', '♠9', '♠10', '♠J', '♠Q', '♠K', '♥A', '♥2', '♥3', '♥4', '♥5', '♥6', '♥7', '♥8', '♥9', '♥10', '♥J', '♥Q', '♥K', '♦A', '♦2', '♦3', '♦4', '♦5', '♦6', '♦7', '♦8', '♦9', '♦10', '♦J', '♦Q', '♦K', '♣A', '♣2', '♣3', '♣4', '♣5', '♣6', '♣7', '♣8', '♣9', '♣10', '♣J', '♣Q', '♣K', 'Joker', 'Joker' ]; let result = cards.map(card => { return { c: card, sort: Math.random() } }).sort((a, b) => a.sort - b.sort).slice(0, 9).map(a => ac); console.log(JSON.stringify(result)); 

    • Funny approach to the problem! (1 line) But we have two Jokers. Your decision is good, but because cards[52]==cards[53] , it can be improved. For example, put "Red Jocker" and "Black Jocker" - Egor Randomize
    • And I haven’t held cards in my hands for a long time, so I don’t remember if the jokers are different from each other. :) Well, in general, there was a thought to generate this array programmatically, but was too lazy :) - Yaant

     var cardsLength = 54; // instead of cards.length var randIds = new Array(9); for (var i = 0; i < randIds.length; i++) { // В таблице 9 строк var used = true; var randomIndex; while (used) { randomIndex = Math.floor(Math.random() * cardsLength); used = randIds.indexOf(randomIndex) != -1; } randIds[i] = randomIndex; } console.log(JSON.stringify(randIds)); 

    • Thank you) endless loops and get out and 3 of it only if there is an element) - Anastasia

    Another option

      var cardsLength = 54; // instead of cards.length var randIds = new Array(9); var cards = new Array(54); // здесь храним карты // Заполняем массив из 54 карт, которые затем будем "вытягивать", их "значениями" от 1 до 54 for (var j = 0; j < 54; j++) cards[j] = j + 1; // for (var i = 0; i < randIds.length; i++) { // В таблице 9 строк var cardIndex; // индекс карты в оставшейся колоде var randomIndex; // номер карты от 1 до 54 // на каждом цикле объем выборки уменьшается (cardsLength - i) // получаем индекс карты из оставшихся в колоде cardIndex = Math.floor(Math.random() * (cardsLength - i)); // получаем номер карты randomIndex = cards[cardIndex]; // добавляем номер карты в выходной массив randIds[i] = randomIndex; // удаляем карту из колоды cards.splice(cardIndex, 1); } console.log(JSON.stringify(randIds));