How do I write a function that takes an array of values and returns an object JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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 ]
}
raja
Published on 26-Aug-2020 09:40:47
Advertisements