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

210
Vistas
generate 4 unique random number in arr?

If I want 4 random number in an array [num1, num2, num3, num4], I can't do

function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

const arr = [getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10), getRandomFloat(1,10)]

because I'll have duplicated value. Is there any way or library that allow me to generate a unique set of randomed number?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can declare the array as empty and then continue adding values to it until it has 4 numbers. You can also avoid duplicates by using if condition.

function getRandomFloat(min, max) {
      return Math.random() * (max - min) + min;
    }
    
    var arr=[];
    var min=1, max=10;
    while (arr.length != 4)  // executes loop till length of array is 4
    {
        var i = getRandomFloat(min, max);
        // checking if number already exists in array
        if (arr.includes(i))
        {
            continue;
        }
        arr.push(i);
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

This is efficient method to achieve this. You can use Set to get the random unique numbers in an array

You can even add a check if unique numbers are possible or not as

  if (max - min < n) return "Not possible";

function getRandomNumbers(n, min = 0, max = 0) {
  const set = new Set();
  while (set.size !== n) {
    set.add(Math.random() * (max - min) + min);
  }
  return [...set];
}

console.log(getRandomNumbers(4, 1, 10));

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