Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

374
Visualizações
JavaScript: How can you select random elements from an array without allowing duplicates?

I am looking to randomly select a number from this array WITHOUT duplicates. There can only be two possibilities for each number as shown in the array, select up to a maximum of 6. This works to select a random number but allows duplicates...

const smallNums = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];

When using the splice() method, each time I generate a number based on a random index, it's removed but shows up again in the array the next time a random is generated

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use a Set to get the unique items in the array.

const smallNums = [...new Set([1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10])]

const randomSmallNumArr = smallNums[Math.floor(Math.random() * smallNums.length)];
console.log(randomSmallNumArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understand your requirement clearly, You want to generate a non-repeating random numbers from an array of numbers ? If Yes, I added a solution below.

// Input array
const arr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10];

// Remove duplicate elements from an array
let uniqueElementsArr = [...new Set(arr)];

// Find out random number from an array
const randomNum = uniqueElementsArr[Math.floor(Math.random()*uniqueElementsArr.length)];

// removing the random number from the existing array so that it should not be replicate.
if (uniqueElementsArr.indexOf(randomNum) !== -1) {
    uniqueElementsArr.splice(uniqueElementsArr.indexOf(randomNum), 1)
}

console.log(randomNum);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda