Reputation: 111
function multipleLetterCount(str){
var finalObj = {};
for(var i = 0; i < str.length; i++){
if(!str[i] in finalObj){
finalObj[str[i]] = 1;
} else {
finalObj[str[i]]++;
}
}
return finalObj;
}
console.log(multipleLetterCount("SomeWord"));
I need help figuring out why the values are coming up as NaN. Thanks
Upvotes: 3
Views: 139
Reputation: 68933
why the values are coming up as NaN
str[i]
represents different character in each iteration. When you negate that character like !str[i]
that becomes false
. Hence the condition (if(false in finalObj)
) is always false
and executes only the else
part. At this point finalObj[str[i]]
is undefined
. Finally, incrementing undefined
(undefined++
) gives you NaN
.
Try with Object.prototype.hasOwnProperty()
which returns a boolean indicating whether the object has the specified property as its own property:
function multipleLetterCount(str){
var finalObj = {};
for(var i = 0; i < str.length; i++){
if(!finalObj.hasOwnProperty(str[i])){
finalObj[str[i]] = 1;
} else {
finalObj[str[i]]++;
}
}
return finalObj;
}
console.log(multipleLetterCount("SomeWord"));
Upvotes: 5
Reputation: 845
How about?
let string = 'SomeWord';
const result = string.split('').reduce((a, b) => {
a[b] ? a[b]++ : a[b] = 1
return a;
}, {});
console.log(result);
Upvotes: 0
Reputation: 769
You can simplify your code like this
function multipleLetterCount(str){
var finalObj = {};
for(var i = 0; i < str.length; i++){
if (finalObj[str[i]]) {
finalObj[str[i]]++;
} else {
finalObj[str[i]] = 1;
}
}
return finalObj;
}
console.log(multipleLetterCount("SomeWord"));
Upvotes: 0
Reputation: 243
Note that there are a plethora of ways to resolve the problem, all of which depend on how robust you need your function to be.
For simplicity, instead of if(!str[i] in finalObj)
, do if (!(str[i] in finalObj))
.
Upvotes: 0