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

195
Vistas
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 Respuestas
Responde la pregunta

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