用于计算JavaScript中以空格分隔的元素的频率的函数

假设我们有一个包含一些字母的字符串,这些字母之间用空格隔开,如下所示:

const str = 'a b c d a v d e f g q';

我们需要编写一个包含一个这样的字符串的JavaScript函数。该函数应准备一个包含字母及其计数的对象频率数组。

示例

为此的代码将是-

const str = 'a b c d a v d e f g q';
const countFrequency = (str = '') => {
   const result = [];
   const hash = {};
   const words = str.split(" ");
   words.forEach(function (word) {
      word = word.toLowerCase();
      if (word !== "") {
         if (!hash[word]) {
            hash[word] = { name: word, count: 0 };
            result.push(hash[word]);
         };
         hash[word].count++;
      };
   });
   return result.sort((a, b) => b.count − a.count)
}
console.log(countFrequency(str));

输出结果

控制台中的输出将是-

[
   { name: 'a', count: 2 },
   { name: 'd', count: 2 },
   { name: 'b', count: 1 },
   { name: 'c', count: 1 },
   { name: 'v', count: 1 },
   { name: 'e', count: 1 },
   { name: 'f', count: 1 },
   { name: 'g', count: 1 },
   { name: 'q', count: 1 }
]
猜你喜欢