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

200
Views
Pop random element from a set - JS

In e.g. Python if we have a set we can call set.pop() and it will remove a value from the set and return it.

I'm working through an algorithms question in JS where I need to do this. But there doesn't seem to be a way to, as the set.delete() function expects a value, and I don't have access to the values. Is there an easy work around?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can iterate over the values. (It would be faster than converting it to an array.)

function deleteRandomElement(set) {
  if (set.size > 0) {
      const randomIndex = Math.floor(Math.random()*set.size);
      let i = 0;
      
      for(const value of set) {
        if(i === randomIndex) {
          set.delete(value);
          break;
        }
        i++;
      }
  }
}
about 4 years ago · Santiago Trujillo Report
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!