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

188
Visualizações
JavaScript: Randomly select a limited number of objects from an array to be placed into a second array?

I am working on a random question generator and am trying to take 5 questions from a large array of objects that looks like this:

const bank= [
{
txt: "This question's unique text...",
choices: 'a', 'b', 'c',
answer: 2
},
{
txt: "This question has different text...",
choices: 'a', 'b', 'c',
answer: 1
},
// and so on for 20 more questions

I used a while loop to limit the number of iterations, I was hoping to limit the selection of exactly 5 objects selected. My loop:

//push the questions into availableQuestions Array
function setAvailableQuestions(){
    const length = 5
    const banklength = bank.length
    while (length > banklength) { length = banklength}  
        for(let i=0; i<length; i++){
            r = Math.floor(Math.random() * banklength)
            availableQuestions.push(bank[r])
            console.log(availableQuestions)
            bank.splice(r, 1)
    }

In the console, I see there is sometimes an 'undefined' object selected. I think it is because I have set up the 'splice'. Additionally, it is iterating 25 times rather than 5. I have been stuck for a couple of days on this . After searching, I have learned about the Fisher-Yates shuffle and tried to run that function first and push the first five questions after, but that didn't work, either. Any point in the right direction is appreciated.

about 4 years ago · Juan Pablo Isaza
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