javascript 使用javascript计算字符串中字符的频率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18619785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:37:22  来源:igfitidea点击:

counting frequency of characters in a string using javascript

javascript

提问by Samrat

I need to write some kind of loop that can count the frequency of each letter in a string.

我需要编写某种循环来计算字符串中每个字母的频率。

For example: "aabsssd"

例如:“aabsssd”

output: a:2, b:1, s:3, d:1

输出:a:2, b:1, s:3, d:1

Also want to map same character as property name in object. Any good idea how to do this?

还想映射与对象中的属性名称相同的字符。任何好主意如何做到这一点?

I am not sure how to do it.

我不知道该怎么做。

This is where I am so far:

这是我到目前为止的地方:

var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function counter(x) {
    var count=0, temp = [];
    x = x.split('');
    console.log(x);
    for(var i=0, len = x.length; i < len; i++) {
        if(x[i] == "a") {
            count++;
        }
    }
    return count;
}
var a = "aabbddd";
console.log(counter(a));

回答by Jonathan Crowe

Here you go:

干得好:

function getFrequency(string) {
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var character = string.charAt(i);
        if (freq[character]) {
           freq[character]++;
        } else {
           freq[character] = 1;
        }
    }

    return freq;
};

回答by russiansummer

some ES6 syntax with reduce:

一些带有 reduce 的 ES6 语法:

let counter = str => {
  return str.split('').reduce((total, letter) => {
    total[letter] ? total[letter]++ : total[letter] = 1;
    return total;
  }, {});
};

counter("aabsssd"); // => { a: 2, b: 1, s: 3, d: 1 }

回答by sarunast

Another solution:

另一种解决方案:

function count (string) {  
  var count = {};
  string.split('').forEach(function(s) {
     count[s] ? count[s]++ : count[s] = 1;
  });
  return count;
}

回答by frederick99

With some ES6 features and short-circuiting:

使用一些 ES6 特性和短路:

const counter = s => [...s].reduce((a,c) => (a[c] = a[c]+1 || 1) && a, {})

counter("hello")  // {h: 1, e: 1, l: 2, o: 1}

回答by vitkon

More declarative way to get a word histogram will be to utilise reduce to iterate through letters and come up with a new object that contains letters as keys and frequencies as values.

获得单词直方图的更明确的方法是利用 reduce 遍历字母并提出一个包含字母作为键和频率作为值的新对象。

function getFrequency(str) {
  return str.split('').reduce( (prev, curr) => {
    prev[curr] = prev[curr] ? prev[curr] + 1 : 1;
    return prev;
  }, {});
};

console.log(getFrequency('test')); // => {t: 2, e: 1, s: 1}

回答by Yoni Rabinovitch

Here's another way:

这是另一种方式:

const freqMap = s => [...s].reduce((freq,c) => {freq[c] = -~freq[c]; return freq} ,{})

Or, if you prefer a "for" loop:

或者,如果您更喜欢“for”循环:

function freqMap(s) { 
   freq={}; 
   for (let c of s) 
      freq[c]=-~freq[c]; 
   return freq;
}

e.g. freqMap("MaMaMia") returns Object{M : 3, a : 3, i : 1}

例如 freqMap("MaMaMia") 返回 Object{M : 3, a : 3, i : 1}

This method leverages the fact that in javascript, bitwise not on "undefined" gives -1, (whereas "undefined+1" gives NaN). So, -~undefined is 1, -~1 is 2, -~2 is 3 etc.

这种方法利用了这样一个事实,即在 javascript 中,按位不在“未定义”上给出 -1,(而“未定义+1”给出 NaN)。所以,-~undefined 是 1,-~1 是 2,-~2 是 3,等等。

We can thus iterate over the characters of the string, and simply increment freq[c] without any "if". The first time we encounter a character c, freq[c] will be undefined, so we set it to -~freq[c] which is 1. If we subsequently encounter c again, we again set freq[c] to -~freq[c], which will now be 2, etc.

因此,我们可以遍历字符串的字符,并简单地增加 freq[c] 而没有任何“if”。第一次遇到字符 c,freq[c] 将是未定义的,因此我们将它设置为 -~freq[c],即 1。如果我们随后再次遇到 c,我们再次将 freq[c] 设置为 -~freq [c],现在是 2,依此类推。

Simple, elegant, concise.

简洁,优雅,简洁。

回答by leerssej

a leaner, functional solution:

一个更精简、更实用的解决方案:

using ES6 Arrows && Logical Operators:

使用 ES6 箭头 && 逻辑运算符:

const buildFreqDict = string =>
  string.split('').reduce((freqDict, char) => {
    freqDict[char] = (freqDict[char] || 0) + 1;
    return freqDict;
  }, {})

console.log(buildFreqDict("banana"))

Explained

解释

  • splitstringinto array of characters.
    • and then feed it into a reducemethod (using method.chaining()).
  • if charis already logged in countDictthen add 1 to it.
    • orif character not found in countDictthen set it to 1.
  • return new values back up to reduce's accumulator object
  • NB: don't forget about including the third argument of .reduce(): in this case it is a {}(object literal) that serves to initialize the freqDictobject.
  • 字符串拆分为字符数组。
    • 然后将其输入到一个reduce方法中(使用method.chaining())。
  • 如果char已经登录countDict则加 1。
    • 或者如果在countDict 中找不到字符,则将其设置为 1。
  • 将新值返回到reduce的累加器对象
  • 注意:不要忘记包含.reduce()的第三个参数:在这种情况下,它是一个{}(对象文字),用于初始化freqDict对象。

for more info see Counting instances of values in an objecthalf way down the page here: MDN Reduce
and for more info about using logical operatorsplease see here: MDN Logical Operators

有关更多信息,请参阅在页面下方的对象中计数值的实例MDN Reduce
以及有关使用逻辑运算符的更多信息,请参阅此处:MDN 逻辑运算符

回答by Sergei Volynkin

// Count frequency of characters in a string
// input: 'Hello, I'm Paul!'
// result: {
//      H: 1,
//      E: 1,
//      L: 3,
//      ... and so on ...
// }

const countChars = (string) => {
    let charStats = {};
    string = string.replace(' ', '').toUpperCase().split('');

    string.forEach((char) => {
        if (charStats[char]) {
            charStats[char]++;
        } else {
            charStats[char] = 1;
        }
    });

    return charStats;
};

回答by bajran

Another Solution

另一种解决方案

    function maxChar(str) {

        const charMap = {};
        let max = 0;
        let maxChar = '';

        for(let char of str){
            if(charMap[char]){
                charMap[char]++;
            }else{
                charMap[char] = 1;
            }
        }

        for(let char in charMap){
            if(charMap[char] > max){
                max = charMap[char];
                maxChar = char;
            }
        }

        return maxChar; 
}

===>

 maxChar('355385') 
  "5"

===>

 maxChar('355385') 
  "5"

回答by Aaron

var str = 'abcccdddd';

function maxCharCount(target) {
    const chars = {};

    let maxChar = '';
    let maxValue = 1;

    for (let char of target) {
        chars[char] = chars[char] + 1 || 1;
    }

    return chars;
}

console.log(maxCharCount(str));