AetherRemnant
AetherRemnant

Reputation: 111

I need help figuring out why I'm getting NaN in this function

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

Answers (4)

Mamun
Mamun

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

Teobis
Teobis

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

Joven28
Joven28

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

Andres Salgado
Andres Salgado

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

Related Questions