在陣列中計算資料型別的數量 - 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
}

更新日期: 16-Sep-2020

171 閱讀量

開啟您的 職業 生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.