js 統計一個字串出現頻率最高的字母/數字
let str = 'asdfg2hjklaqw2ert2yuiopbiaia21bbbb54562102bbbbbbbb0a124a511a22a2a242a1a';
let countRateResult = countRate(str);
console.log("countRateResult", countRateResult)
// 自寫的low方法
function countRate(arr) {
// arr.split('') 如果括號裡頭是空字串,將會返回字串中每個字元的陣列形式
let strArray = arr.split('');
// let countArr = {};// 也可以存為key-value形式
let countArr = [];
strArray.forEach((item, index)=>{
// countArr[item] = 0;
countArr[index] = 0
for(let i=0; i<strArray.length; i++) {
if (item == strArray[i]) {
// countArr[item]++;
countArr[index]++;
}
}
});
let countArrResultName = strArray[0];// 先讓最大值和數為陣列第一個
let countArrResultNum = countArr[0];
for(let i=0; i<countArr.length; i++) {
if (countArr[i] > countArrResultNum) {
countArrResultName = strArray[i];
countArrResultNum = countArr[i];
}
}
return [countArrResultName, countArrResultNum];
}
複製程式碼
忘了是哪個網址了,看到個別人寫的更好的寫法,記錄一下
// 方法1
let str = 'asdfghjklaqwertysddfsdewffffffadfsdfeererefdfefuiopiaia';
const strChar = str => {
let string = [...str],
maxValue = '',
obj = {},
max = 0;
string.forEach(value => {
obj[value] = obj[value] == undefined ? 1 : obj[value] + 1;// 亮點
if (obj[value] > max) {
max = obj[value]
maxValue = value
}
})
console.log("obj", obj);
return maxValue;
}
console.log(strChar(str));
// 方法2
let str = 'safaA890654uasfAJIFj32342HDWEFH3Da23AueUEWda';
let results = {};
let rs = str.split('');
rs.forEach(function(al){
if(results[al] === undefined){
results[al] = 1;
}else{
results[al]++;
}
})
let keys = Object.keys(results);
for(let i = 0; i < keys.length; i++){
console.log(keys[i] + ' : ' + results[keys[i]]);
}
複製程式碼