Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!