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

269
Visualizações
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 Respostas
Responde à pergunta

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 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