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

72
Visualizações
incrementing an object in a while loops

input: ["doc", "doc", "image", "doc(1)", "doc"]

output: ["doc", "doc(1)", "image", "doc(1)(1)", "doc(2)"]

The issue:

{used[name]++} this part of the code is tricking me.

I don't understand line and how I'm not assigning 1 to the first thing

the code is working the way it should from trial and error; but I'm having a hard to wrapping my brain around this loop.

my understanding:

we loop through the names, then each name that starts with docs; we assign newName to doc1

What I tried:

used[newName] = 6;

results: [doc, doc(6), image, doc(1), doc(7)]

this ended up confusing me more. it's late and I might just need some sleep.


const solution = names => {
    const used = {};
    return names.map(name => {
        let newName = name;
        while (used[newName]) {
            newName = `${name}(${used[name]++})`;
        }
        used[newName] = 1;
        return newName;
    });
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The first time a name is encountered used[newName] is undefined, so the while loop doesn't even start, and newName is returned. In the next time it's encountered, you already have user[newName]=1, so (1) is appended to the name, and so on.

about 4 years ago · Juan Pablo Isaza 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