2 回答

TA貢獻1776條經驗 獲得超12個贊
我建議像這樣簡單地減少
var inputString = 'donald duck';
var result = inputString.split('').reduce((acc, char, index) => {
if (acc[char] !== undefined) {
acc[char] = acc[char] + 1;
}
else {
acc = { ...acc, [char]: 1 }
}
return acc
}, {})
參見: https: //jsfiddle.net/yswu91zh/21/

TA貢獻1951條經驗 獲得超3個贊
僅遞歸不會給您所需的輸出。遞歸計算字符后,您必須按頻率排序,然后按字符排序。我已經從計數中排除了一堆帶空格的標點符號,如果您想排除更多,只需將其添加到標點符號字符串中即可。你必須使用String.prototype.localeCompare()方法來比較字符。此方法比較當前區域設置中的兩個字符串。當您使用丹麥語時,您必須將區域設置指定為da。
const punctuations = '.,:;!? ';
const countCharInString = (str, p = {}) => {
if (str.length === 0) return p;
const key = str[0].toLowerCase();
if (!punctuations.includes(key)) {
if (!p[key]) p[key] = 1;
else p[key] += 1;
}
return countCharInString(str.slice(1), p);
};
const cmp = (x, y) => {
if (x[1] === y[1]) {
return x[0].localeCompare(y[0], 'da');
}
return x[1] < y[1] ? 1 : -1;
};
const ret = Object.fromEntries(
Object.entries(countCharInString('Vi skal t?lle bogstaver')).sort(cmp)
);
console.log(ret);
添加回答
舉報