在数组中计算数据类型的数量 - 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.