Count the number of data types in an array - JavaScript


We are required to write a JavaScript function that takes in an array that contains elements of different data types and the function should return a map representing the frequency of each data type.

Let’s say the following is our array −

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

Example

Following is the code −

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));

Output

Following is the output in the console −

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

Updated on: 16-Sep-2020

156 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements