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

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