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

199
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
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