into-piece / Step-By-Step

每天一题向前端架构师前进
4 stars 1 forks source link

判断字符串中出现次数最的字符,并统计字符 #9

Open into-piece opened 5 years ago

into-piece commented 5 years ago
function countString(string) {
  let arr = string.split("");
  let obj = arr.reduce((res, cur, index) => {
    res = {
      ...res,
      [cur]: res[cur] ? res[cur] + 1 : 1
    };
    if (index === arr.length - 1) {
      let biggst = {};
      for (let i in res) {
        if (!biggst.num || biggst.num < res[i]) {
          biggst = {
            index: i,
            num: res[i]
          };
        }
      }
      return biggst;
    } else {
      return res;
    }
  }, {});
  return obj;
}
let result = countString("12345678912111111");
console.log(result, "=================");