Reputation: 169
I have this function:
var majorityElement = function(nums) {
let count = {}
for(i=0; i < nums.length; i++){
let x = nums[i];
count[x] ? count[x] + 1 : count[x] = 1
}
console.log(count)
return Object.keys(count).reduce((a,b) => count[a] > count[b] ? a : b)
};
So, I don't understand why the count doesn't really work, if I run it the count would look something like this for this array [3,3,4]
:
count{
3: 1
4: 1
}
Shouldn't it be 3:2 and 4:1?
Upvotes: 1
Views: 40
Reputation: 49945
The assignment should be on the left handside so instead of:
count[x] ? count[x] + 1 : count[x] = 1
try:
count[x] = count[x] ? (count[x] + 1) : 1
var majorityElement = function(nums) {
let count = {}
for(i=0; i < nums.length; i++){
let x = nums[i];
count[x] = count[x] ? (count[x] + 1) : 1
}
console.log(count)
return Object.keys(count).reduce((a,b) => count[a] > count[b] ? a : b)
};
console.log(majorityElement([3,3,4]))
Upvotes: 3