This page looks best with JavaScript enabled

GroupBy in Array using Reduce in Javascript

 ·   ·  ☕ 2 min read

There is a really cool way to do group by in an array using reduce.

The problem statement - you have an array of objects and need to create different arrays based on similar attributes. This is very similar to the SQL group by statement.

Consider the example array -

1
2
3
4
5
6
const fruits = [
  (apple = { color: "red", shape: "round" }),
  (watermelon = { color: "green", shape: "square" }),
  (orange = { color: "orange", shape: "round" }),
  (pear = { color: "green", shape: "pear" })
];

We have to group by color - all reds in one array, greens in next array and so forth. This can of course be done with a multiple, nested for loops. Or, you can push the array through a reduce statement that is fed an interesting function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const res = fruits.reduce((acc, item) => {
  const index = fruit => fruit.color(item);
  if (!acc[index]) {
    acc[index] = [];
  }
  acc[index].push(item);
  return acc;
}, {});

console.log(res);

/* output
    {
    red: [ { color: 'red', shape: 'round' } ],
    green: [
        { color: 'green', shape: 'square' },
        { color: 'green', shape: 'pear' }
    ],
    orange: [ { color: 'orange', shape: 'round' } ]
    }
*/
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things