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