prototip,
... тут не переводимый на русский комментарий.
let input = "aaa bb bb rrrrr aaa r t";
function countWords(str, number){
str = str.split(" ");
const obj = str.reduce((a, b) => (a[b] = (a[b]||0) + 1, a), {});
str = Object.keys(obj).sort((a, b) => (obj[b] - obj[a]) || (b.length - a.length));
if(number == void 0) number = str.length;
return str.slice(0, number).map(a => [a, obj[a]]);
}
alert(JSON.stringify(countWords(input)));
или так
let input = "aaa bb bb rrrrr aaa r t";
function countWords(str){
str = str.split(" ");
const obj = str.reduce((a, b) => (a[b] = (a[b]||0) + 1, a), {});
return Object.entries(obj).sort((a, b) => b[1] - a[1]);;
}
alert(JSON.stringify(countWords(input)));