
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Separate Data Types from Array into Groups in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of mixed data types. Our function should return an object that contains data type names as key and their value as array of elements of that specific data type present in the array.
Example
Following is the code −
const arr = [1, 'a', [], '4', 5, 34, true, undefined, null]; const groupDataTypes = (arr = []) => { const res = {}; for(let i = 0; i < arr.length; i++){ const el = arr[i]; const type = typeof el; if(res.hasOwnProperty(type)){ res[type].push(el); }else{ res[type] = [el]; }; }; return res; }; console.log(groupDataTypes(arr));
Output
Following is the console output −
{ number: [ 1, 5, 34 ], string: [ 'a', '4' ], object: [ [], null ], boolean: [ true ], undefined: [ undefined ] }
Advertisements