Return a map representing the frequency of each data type in an array in 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];

Understanding the Problem

We need to count how many times each JavaScript data type appears in the array. JavaScript's typeof operator will help us identify the data type of each element.

Solution Using Map and reduce()

The most efficient approach is to use the reduce() method with a Map object to accumulate the counts:

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
}

How It Works

The function uses reduce() to iterate through the array and build a Map:

  • typeof val determines the data type of each element
  • If the data type already exists in the map, increment its count
  • If it's a new data type, set its count to 1
  • Return the accumulated Map object

Alternative Approach Using Object

You can also use a plain object instead of a Map:

const countDataTypesObj = arr => {
   return arr.reduce((acc, val) => {
      const dataType = typeof val;
      acc[dataType] = (acc[dataType] || 0) + 1;
      return acc;
   }, {});
};

const arr = [23, 'df', undefined, null, 12];
console.log(countDataTypesObj(arr));
{ number: 2, string: 1, undefined: 1, object: 1 }

Key Points

  • typeof null returns "object" in JavaScript (known quirk)
  • Arrays also return "object" with typeof
  • Map preserves insertion order and handles any key type
  • Plain objects work well for string keys like data type names

Conclusion

This solution efficiently counts data types using reduce() and Map. The typeof operator identifies each element's type, and the Map accumulates the frequencies for analysis.

Updated on: 2026-03-15T23:19:00+05:30

158 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements