Determining character frequency in a string (Javascript)
javascript
Solution
Because the property values in `frequencies` have an initial value of `undefined` and `undefined + 1` == `NaN`
Try code like this:
var charFreq = function (frequencyString) {
var stringArray = frequencyString.split("");
var frequencies = {};
for (var k in stringArray) {
var nowLetter = stringArray[k];
if (stringArray.hasOwnProperty(k)) {
// One way to initialize the value -- not the only way.
if (!frequencies[nowLetter]) {
frequencies[nowLetter] = 0;
}
frequencies[nowLetter] += 1;
}
}
return frequencies;
}
Problem
I'm working on a solution for determining character frequency in a string. The characters are being added to my object properly but all counts end up as NaN. (I think I'm taking a less efficient approach by splitting the string into an array of characters, but I'd like to solve this approach nonetheless.) ``` var charFreq = function (frequencyString) { var stringArray = frequencyString.split(""); var frequencies = {}; for (var k in stringArray) { var nowLetter = stringArray[k]; if (stringArray.hasOwnProperty(k)) { frequencies[nowLetter] += 1; } } return frequencies; } charFreq("what is the reason for this"); ```