Let’s say, we are required to write a function classifyArray() that takes in an array which contains mixed data types and returns a Map() with the elements grouped by their data types.
For example −
// if the input array is: const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo'), true, false, 'name', 6]; // then the output Map should be: Map(5) { 'string' => [ 'class', 'name' ], 'number' => [ 2, 6 ], 'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ], 'symbol' => [ Symbol(foo) ], 'boolean' => [ true, false ] }
Now let’s write the code for this function −
Example
const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo'), true, false, 'name', 6]; const classifyArray = arr => { return arr.reduce((acc, val) => { const previousData = acc.get(typeof val); if(previousData){ acc.set(typeof val, [...previousData, val]); }else{ acc.set(typeof val, [val]); }; return acc; }, new Map()); }; console.log(classifyArray(arr));
Output
The output in the console will be −
Map(5) { 'string' => [ 'class', 'name' ], 'number' => [ 2, 6 ], 'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ], 'symbol' => [ Symbol(foo) ], 'boolean' => [ true, false ] }