使用 JavaScript 按順序儲存整數的計數


假設,我們有一個表示類似於下面這樣的數字的長字串−

const str = '11222233344444445666';

我們需要編寫一個 JavaScript 函式接收這樣的字串。我們的函式應該返回一個物件,該物件應該為字串中的每個唯一數字分配唯一的“id”屬性,以及一個其他屬性“count”,該屬性儲存數字在字串中出現的次數。

因此,對於上面的字串,輸出應如下所示 −

const output = {
   '1': { id: '1', displayed: 2 },
   '2': { id: '2', displayed: 4 },
   '3': { id: '3', displayed: 3 },
   '4': { id: '4', displayed: 7 },
   '5': { id: '5', displayed: 1 },
   '6': { id: '6', displayed: 3 }
};

示例

程式碼如下 −

const str = '11222233344444445666';
const countNumberFrequency = str => {
   const map = {};
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(map.hasOwnProperty(el)){
         map[el]['displayed']++;
      }else{
         map[el] = {
            id: el,
            displayed: 1
         };
      };
   };
   return map;
};
console.log(countNumberFrequency(str));

輸出

並且控制檯中的輸出將為 −

{
   '1': { id: '1', displayed: 2 },
   '2': { id: '2', displayed: 4 },
   '3': { id: '3', displayed: 3 },
   '4': { id: '4', displayed: 7 },
   '5': { id: '5', displayed: 1 },
   '6': { id: '6', displayed: 3 }
}

更新於: 2020 年 11 月 21 日

118 次瀏覽

開啟你的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.