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

192
Vistas
Incrementing values in a JavaScript object in a for loop

A particular problem asked to return the first unique value (i.e. a value that appears only once in an array). My approach was to create an obj with keys as elements in the array and the values as a counter for how many times each value was seen.

function solution(arr) {
  let uniqueObj = {}
  for (let i=0; i<arr.length; i++){
    if(uniqueObj[arr[i]] !== undefined){
      uniqueObj[arr[i]] = uniqueObj[arr[i]] + 1
    }
    uniqueObj[arr[i]] = 1
  }
  console.log(uniqueObj) 
}
solution([4,10,5,4,2,10])

//output { '2': 1, '4': 1, '5': 1, '10': 1 }

why isn't the value incrementing each time the same key is seen?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

After your if statement you're resetting uniqueObj[arr[i]] back to 1. You need add an else clause for when uniqueObj doesn't have the value at arr[i]:


if (uniqueObj[arr[i]] !== undefined) {
    uniqueObj[arr[i]] += 1;
} else { // add else block
    uniqueObj[arr[i]] = 1      
}

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