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

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 ?

Using Array.reduce() with Map

The most efficient approach uses reduce() to build a Map that groups elements by their data type:

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));
Map(5) {
   'string' => [ 'class', 'name' ],
   'number' => [ 2, 6 ],
   'object' => [ [ 7, 8, 9 ], { name: 'Michael' } ],
   'symbol' => [ Symbol(foo) ],
   'boolean' => [ true, false ]
}

How It Works

The function uses reduce() to iterate through the array and accumulate results in a Map:

  1. typeof val determines the data type of each element
  2. acc.get(typeof val) checks if this type already exists in the Map
  3. If it exists, spread the previous array and add the new value
  4. If not, create a new array with just the current value

Alternative: Using Object Instead of Map

You can also return a plain object instead of a Map:

const classifyArrayToObject = arr => {
    return arr.reduce((acc, val) => {
        const type = typeof val;
        acc[type] = acc[type] ? [...acc[type], val] : [val];
        return acc;
    }, {});
};

const arr = ['class', 2, [7, 8, 9], {"name": "Michael"}, Symbol('foo')];
console.log(classifyArrayToObject(arr));
{
  string: [ 'class' ],
  number: [ 2 ],
  object: [ [ 7, 8, 9 ], { name: 'Michael' } ],
  symbol: [ Symbol(foo) ]
}

Comparison

Approach Return Type Use Case
Map-based Map object Better for iteration, maintains insertion order
Object-based Plain object Simpler access with dot notation, JSON serializable

Conclusion

Use Array.reduce() with typeof to efficiently group array elements by data type. Choose Map for better iteration or plain objects for simpler property access.

Updated on: 2026-03-15T23:18:59+05:30

618 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements