Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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];
Understanding Data Types in JavaScript
JavaScript's typeof operator returns string representations of data types. Note that arrays and null both return "object", which is a known quirk of JavaScript.
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
}
How It Works
The function uses reduce() to iterate through the array and build a Map. For each element, it gets the data type using typeof and either increments the existing count or sets it to 1 for new types.
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;
}, {});
};
console.log(countDataTypesObj(arr));
{
number: 3,
string: 2,
undefined: 1,
object: 4,
symbol: 1
}
Key Points
- Arrays, objects, and
nullall return"object"fromtypeof - The
Mapapproach provides better key handling than plain objects - Both approaches use
reduce()for efficient single-pass counting
Conclusion
This solution efficiently counts data types using reduce() and Map. The typeof operator groups arrays, objects, and null together as "object" type.
