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

267
Vistas
How to generate a random array in JS?

I need to generate a different array each time in JS , where it's length should be exact 16 elements , each element should be between 0 to 7 , and each element should occur exactly twice. for eg. [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7] or [0,1,2,3,4,5,6,7,7,6,5,4,3,2,1,0]

I need a function that will generate different array each time.

let sequence=[0,1,2,3,4,5,6,7]
let seq1=[0,1,2,3,4,5,6,7]
let seq2=[0,1,2,3,4,5,6,7]
let arr1=[]
let arr2=[]
let arr3

function generateArray(arr,seq){
    for(let i=0;i<8;i++){
        let numb=Math.trunc(Math.random()*(seq.length))
        arr.push(seq[numb])
        seq.splice(numb,1)
    }
}

generateArray(arr1,seq1)
generateArray(arr2,seq2)

arr3=[...arr1,...arr2]
console.log(arr3)

I've used the above function , but the drawback is that it firsts generates randomly all the numbers from 0 to 7 , and then does the same again.

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

0

There's two functions:

  • xArray(num) Instantiates a new Array and fills it with consecutive numbers to the given length

  • shuffle(arr) It shuffles any type of Array using the Fisher–Yates shuffle algorithm

const xArray = x => [...new Array(x)].map((_, i) => i);

const shuffle = array => {
  let qty = array.length, temp, i;
  while (qty) {
    i = Math.floor(Math.random() * qty--);
    temp = array[qty];
    array[qty] = array[i];
    array[i] = temp;
  }
  return array;
};

let a = shuffle(xArray(8));
let b = shuffle(xArray(8));

console.log([...a, ...b]);

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