JavaScript: Grouping array objects by property without reduce function

I’m working on a JavaScript project and need to group objects from an array based on a common property. The thing is, I want to avoid using the reduce method for this task. Can someone show me alternative ways to achieve this?

Here’s my sample data:

const employees = [
  { employee: 'John', department: 'HR' },
  { employee: 'Sarah', department: 'IT' },
  { employee: 'Mike', department: 'HR' },
  { employee: 'Lisa', department: 'IT' },
  { employee: 'Tom', department: 'Finance' }
];

I want the result to look like this:

console.log(groupedData);

// {
//   'HR': [{ employee: 'John', department: 'HR' }, { employee: 'Mike', department: 'HR' }],
//   'IT': [{ employee: 'Sarah', department: 'IT' }, { employee: 'Lisa', department: 'IT' }],
//   'Finance': [{ employee: 'Tom', department: 'Finance' }]
// }

What are some good approaches to accomplish this grouping without relying on the reduce method?

I just use a basic for loop with property checking. Works great and it’s easy to read:

function groupByProperty(array, property) {
  const result = {};
  for (let i = 0; i < array.length; i++) {
    const key = array[i][property];
    if (!result[key]) {
      result[key] = [];
    }
    result[key].push(array[i]);
  }
  return result;
}

const groupedEmployees = groupByProperty(employees, 'department');

You get full control over the loop and debugging is way easier. Really handy with large datasets since you can add conditions or break early. Plus it’s faster than functional approaches.

Map’s another solid option - gives you better structure. I use this when I need better key management:

function groupByDepartment(employees) {
  const map = new Map();
  for (const emp of employees) {
    if (!map.has(emp.department)) {
      map.set(emp.department, []);
    }
    map.get(emp.department).push(emp);
  }
  return Object.fromEntries(map);
}

Map handles edge cases better than plain objects, especially with weird strings or numbers as property values. Converting back to an object keeps it compatible with existing code.

forEach works great if you don’t want reduce but still like the functional approach. Just start with an empty object and iterate:

const grouped = {};
employees.forEach(emp => {
  if (!grouped[emp.department]) grouped[emp.department] = [];
  grouped[emp.department].push(emp);
});

Clean and readable - no index management hassles.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.