![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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];
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 }
Advertisements