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 to return a map representing the frequency of each datatype −
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
The output in the console will be −
Map(5) {
'number' => 3,
'string' => 2,
'undefined' => 1,
'object' => 4,
'symbol' => 1
}