Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

186
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!