元素頻率分佈 - JavaScript


我們需要編寫一個包含以下字串的 Javascript 函式 −

const str = 'This string will be used to calculate frequency distribution';

我們需要返回描述陣列中存在各種元素的頻率分佈的物件。

示例

以下是程式碼 −

const str = 'This string will be used to calculate frequency
distribution';
const frequencyDistribution = str => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      map[str[i]] = (map[str[i]] || 0) + 1;
   };
   return map;
};
console.log(frequencyDistribution(str));

輸出

以下是控制檯中的輸出 −

{
   T: 1,
   h: 1,
   i: 6,
   s: 4,
   ' ': 8,
   t: 5,
   r: 3,
   n: 3,
   g: 1,
   w: 1,
   l: 4,
   b: 2,
   e: 5,
   u: 4,
   d: 2,
   o: 2,
   c: 3,
   a: 2,
   f: 1,
   q: 1,
   y: 1
}

更新於: 18-Sep-2020

931 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.