I've been able to create a frequency map for the letter frequency count for a string:
function letterFrequency(text){
text = text.toLowerCase();
let map = {};
let array = text.split('');
array.forEach((value, index) => {
if (!map[value]) {
map[value] = 0;
}
map[value] += 1;
});
return Object.entries(map).filter((el) => el[0] !== ' ')
//sorts array according to count
.sort((a, b) => b[1] - a[1]);
//how to sort alphabetically when letters have same count?
}
console.log(letterFrequency('aaAabb dddDD hhcc'));
But I've not been able to figure out how to sort alphabetically when frequency counts are the same.
I.e.
[['d',5], ['a',4], ['b',2], ['h',2], ['c',2]]
Should instead be:
[['d',5], ['a',4], ['b',2], ['c',2], ['h',2]]
How can I keep frequency count as the main sorting priority, but then also sort alphabetically after sorting by frequency?
Also trying this unfortunately did not have any effect:
function letterFrequency(text){
text = text.toLowerCase();
let map = {};
let array = text.split('');
array.forEach((value, index) => {
if (!map[value]) {
map[value] = 0;
}
map[value] += 1;
});
return Object.entries(map).filter((el) => el[0] !== ' ')
.sort((a, b) => b[1] - a[1])
.sort((a, b) => a[0] - b[0]);
}