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
Separating data type from array into groups in JavaScript
In JavaScript, you often need to group array elements by their data types. This is useful for data analysis, validation, or organizing mixed-type arrays. We'll create a function that separates elements into groups based on their typeof result.
Problem
We need to write a JavaScript function that takes an array of mixed data types and returns an object where each key represents a data type and its value is an array containing all elements of that type.
Solution
Here's how to group array elements by their data types:
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));
{
number: [ 1, 5, 34 ],
string: [ 'a', '4' ],
object: [ [], null ],
boolean: [ true ],
undefined: [ undefined ]
}
How It Works
The function iterates through each array element and uses typeof to determine its data type. For each type, it either creates a new array or adds to an existing one in the result object.
Alternative Approach Using forEach
Here's a more concise version using forEach():
const groupDataTypesForEach = (arr = []) => {
const result = {};
arr.forEach(element => {
const type = typeof element;
result[type] = result[type] || [];
result[type].push(element);
});
return result;
};
const testArr = [42, 'hello', {}, true, null, undefined, 3.14];
console.log(groupDataTypesForEach(testArr));
{
number: [ 42, 3.14 ],
string: [ 'hello' ],
object: [ {}, null ],
boolean: [ true ],
undefined: [ undefined ]
}
Key Points
-
typeof nullreturns"object"in JavaScript, so arrays and null are grouped together - The function handles empty arrays and returns an empty object
- Each data type becomes a key in the result object
- Elements maintain their original order within each type group
Conclusion
This approach efficiently groups array elements by data type using typeof. It's particularly useful for data preprocessing and type validation in JavaScript applications.
