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
Selected Reading
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
} Advertisements
