I have been working on developing a function that is capable of counting the matches of each letter of the alphabet in a given string. Once I obtain these counts, my goal is to store them in an associative array for easy reference.
However, the issue arises when I use the
string.match(regExpression) || [].length
code snippet, as it returns an array rather than the expected integer value representing the length of the match. My understanding was that the string.prototype.match() method, although returning an array, should still allow me to retrieve the length as a number based on the formal description of the method.
I am curious to know what mistake I might be making in this code implementation?
function countLetters(string) {
//create array with letters of the alphabet
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
var counts = [];
for (i = 0; i < alphabet.length; i++) {
var regExpression = new RegExp(alphabet[i], "g");
counts[alphabet[i]] = string.match(regExpression) || [].length;
}
return counts;
}