Cheese Cheese - 20 days ago 5
Javascript Question

Javascript count characters case insensitive

I have to count how many times each letter appears in a string.
Case insensitive.


For example:


var str = "aaaAAAbbB"


would print "A: 6, B: 3"


This is what I have but it counts lower case and upper case as separate.



var string = document.getElementById("text").value
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++)
{
ch = string.charAt(index);
count = counts[ch];
counts[ch] = count ? count + 1 : 1;
}
for (ch in counts)
{
console.log(ch+" count: "+counts[ch]);
}

Answer

You could change the character to upper or lower case for counting.

ch = string.charAt(index).toUpperCase();
//                       ^^^^^^^^^^^^^^

var string = "aaaAAAbbB";
var counts = {};
var ch, index, length, count;
for (index = 0, length = string.length; index < length; index++) {
    ch = string.charAt(index).toUpperCase();
    count = counts[ch];
    counts[ch] = count ? count + 1 : 1;
}
for (ch in counts) {
    console.log(ch + " count: " + counts[ch]);
}

Compacter style

var string = "aaaAAAbbB",
    counts = {};

string.split('').forEach(function (c) {
    counts[c.toUpperCase()] = (counts[c.toUpperCase()] || 0) + 1;
});

console.log(counts);