如何统计数组中单词的字符数?

3

我有一个数组["academy"],我需要计算数组中字符串的字符数。

输出:

a:2
c:1
d:1
e:1
m:1
y:1

像这样

我尝试了两个for循环

function sumChar(arr){
    let alph="abcdefghijklmnopqrstuvxyz";
    let count=0;
    for (const iterator of arr) {
        for(let i=0; i<alph.length; i++){
            if(iterator.charAt(i)==alph[i]){
                count++;
                console.log(`${iterator[i]} : ${count}`);
                count=0;
            }
        }
    }
}
console.log(sumChar(["abdulloh"]));

它工作不正常

a : 1
b : 1
h : 1
undefined

我添加了一个答案,希望它能符合您的期望。 - Rohìt Jíndal
4个回答

0

你也可以使用正则表达式来检查出现次数。在这里,我编写了一个方法来检查字符串中的字符。希望它有所帮助。

word: string = 'abcdefghijklkmnopqrstuvwxyzgg';
charsArrayWithCount = {};
CheckWordCount(): void {
    for(var i = 0;i < this.word.length; i++){
        if(this.charsArrayWithCount[this.word[i]] === undefined){
            this.charsArrayWithCount[this.word[i]] = this.charCount(this.word, this.word[i]);
        }
    }
    console.log(this.charsArrayWithCount);
}
charCount(string, char) {
    let expression = new RegExp(char, "g");
    return string.match(expression).length;
}

0
这里有一个简洁的方法。 [...new Set(word.split(''))] 创建了一个省略任何重复字母的字母数组。 .map 从该数组中取出每个字母并将其通过长度检查器运行。 ({ [m]: word.split(m).length - 1 }) 将该字母设置为对象键,而word.split(m).length - 1是一种快速确定该字母出现次数的方法。

const countLetters = word => (
  [...new Set(word.split(''))].map(m => ({
    [m]: word.split(m).length - 1
  })))

console.log(countLetters("academy"))


0

你可以通过 Array.reduce() 方法简单地实现这个需求。

在线演示 :

const arr = ["academy"];

const res = arr.map(word => {
  return word.split('').reduce((obj, cur) => {
    obj[cur] = obj[cur] ? obj[cur] + 1 : 1
        return obj;
  }, {});
});

console.log(res);


0

我认为这是最简单的方法:

const input = 'academy';

const res = {};

input.split('').forEach(a => res[a] = (res[a] ?? 0) + 1);

console.log(res);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接