Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

375
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda