Computer >> Computer tutorials >  >> Programming >> Javascript

Separating data type 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 ]
}