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");
Freq will be used to maintain the count of each character present in the string. Now, iterate through the string to compare each character with rest of the string. Increment the count of corresponding element in freq. Finally, iterate through freq to display the frequencies of characters.
Example: Find Frequency of CharacterWe loop through each character in the string using charAt() function which takes the index ( i ) and returns the character in the given index. We compare each character to the given character ch . If it's a match, we increase the value of frequency by 1.
const str = 'This string will be used to calculate frequency distribution'; We need to return an object that represents the frequency distribution of various elements present in the array.
match() One of the solution can be provided by the match() function, which is used to generate all the occurrences of a string in an array. By counting the array size that returns the number of times the substring present in a string.
Your frequencies
is an object and when you access
frequencies[nowLetter] += 1;
you are accessing a previously unavailable property like frequencies.a
which will be undefined
. Hence you are getting NaN.
See http://jsfiddle.net/xbUtR/ for the fix.
if(frequencies[nowLetter] === undefined)
frequencies[nowLetter] = 0;
frequencies[nowLetter] += 1;
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With