Hello,
I’m writing a javascript program where I’m counting the number of occurrences of each character in a string.
For example “hello world”:
charArray['h'] = 1;
charArray['e'] = 1;
charArray['l'] = 3;
charArray['o'] = 2;
charArray['w'] = 1;
charArray['r'] = 1;
charArray['d'] = 1;
charArray[''] = 1;
Is there a way to sort this array by the number values in descending order? Writing a custom sort() doesn’t seem to work with string indexes. Perhaps I should store the information in a different format? Two-Dimensional array?
Any help is greatly appreciated.
Thanks.
I would normally have a second array of the letters in you charArray for example
indxCharArray[0] = ‘h’
indxCharArray[1] = ‘e’
indxCharArray[2] = ‘l’
indxCharArray[3] = ‘o’
indxCharArray[4] = ‘w’
indxCharArray[5] = ‘o’
indxCharArray[6] = ‘r’
indxCharArray[7] = ‘d’
indxCharArray[8] = ’ ’
and then sort that array based on the value of charArray[indxCharArray[i]]
mrhoo
November 13, 2010, 12:46pm
3
This is a bit much for ‘hello world’, I admit, but maybe you have longer strings.
function charcount(s, ci){
if(ci) s= s.toLowerCase(); // optional
s= s.replace(/[^a-zA-Z]+/g,''); // optional
var a= s.split('').sort(), b= [], tem, count;
while(a.length){
tem= a.shift();
count= 1;
while(a[0]== tem){
++count;
a.shift();
}
if(!b[count]) b[count]= [count];
b[count].push(tem);
}
for(var i= 0, L= b.length; i<L; i++){
tem= b[i];
if(tem) a.push(tem.shift()+': '+tem.join(', '));
}
return a.sort(function(a, b){
return parseInt(b)-parseInt(a);
});
}
//test
var s= "hello world";
alert('Character count\
\ '+charcount(s, true).join('\
\ '))
/* returned value:
Character count
3: l
2: o
1: d, e, h, r, w
*/