Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

输入一串字符串,根据字符串求出每个字母的数量并返回结果对象。(数字为1时可省略

Sunny-117 opened this issue · comments

commented
function main(str){
    const len = str.length;
    const map = new Map();
    const res = {};
    for(let i = 0; i < len; ++i){
        map.has(str.charAt(i)) ? map.set(str.charAt(i), map.get(str.charAt(i)) + 1) : map.set(str.charAt(i), 1);
    }
    for (const key of map.keys()) {
        res[key] = map.get(key);
    }
    return res;
}
commented
const low = new Array(26).fill(10).map((item, index) => (item + index).toString(36));
const ups = low.map(item => item.toLocaleUpperCase());
const words = [...low, ...ups];

function getWordCount(str) {
  const res = {};
  words.forEach(item => res[item] = 0);
  words.forEach(item => { res[item] = str.length - str.replaceAll(new RegExp(item, 'g'), '').length });
  return res;
}
const a = 'sjhdgsjjdgsjhvdsjhdhsafyqwpqyjdjhdgjshgds';
console.log(getWordCount(a));
function countLetters(str) {
    var result = {};
    for (var i = 0; i < str.length; i++) {
        var letter = str[i];
        if (!result[letter]) { 
            result[letter] = 1;
        } else {
            result[letter]++;
        }
    }
    
    // 遍历结果对象,将值为1的属性删除
    for(var key in result){
      if(result[key] === 1){
         delete result[key];
      }
    }

    return result;
}

console.log(countLetters("hello world")); // { l: 3, o: 2 }
const str = 'syuidfhasdffghjkgutweryerfgdcgertsdfghasdfad'

function getCharNum(str) {
  const tempList = str.split('')
  const map = tempList.reduce((p,c) => {
    if(p[c]) {
      p[c] += 1
    } else {
      p[c] = 1
    }
    return p
  }, {})
  Object.keys(map).forEach(key => {
    if(map[key] === 1) {
      delete map[key]
    }
  })
  return map
}

getCharNum(str)