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

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

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