返回 JavaScript 中陣列中每個資料型別的頻率圖


我們需要編寫一個 JavaScript 函式,該函式接收一個包含不同資料型別元素的陣列,並且該函式應返回一個表示每個資料型別頻率的對映圖。

假設我們有以下陣列 −

const arr = [23, 'df', undefined, null, 12, {
   name: 'Rajesh'
}, [2, 4, 7], 'dfd', null, Symbol('*'), 8];

示例

以下是返回表示每個資料型別頻率的對映圖的程式碼 −

const arr = [23, 'df', undefined, null, 12, {
   name: 'Rajesh'
}, [2, 4, 7], 'dfd', null, Symbol('*'), 8];
const countDataTypes = arr => {
   return arr.reduce((acc, val) => {
      const dataType = typeof val;
      if(acc.has(dataType)){
         acc.set(dataType, acc.get(dataType)+1);
      }else{
         acc.set(dataType, 1);
      };
      return acc;
   }, new Map());
};
console.log(countDataTypes(arr));

輸出

控制檯中的輸出將為 −

Map(5) {
   'number' => 3,
   'string' => 2,
   'undefined' => 1,
   'object' => 4,
      'symbol' => 1
}

更新於: 19-Oct-2020

85 人瀏覽

職業生涯進階

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.