DEV Community

Vivek Kumar
Vivek Kumar

Posted on

Javascript Object.groupBy(), an important method

Most of the time we use some third party library like underscore or lodash, to group an array of objects based on some property.

But did you know that we can also do this directly with JavaScript, since the JavaScript has a special method called .groupBy().

groupBy() is a static method on Javascript 'Object'.

Object properties

Lets take an example-

const products = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];
Enter fullscreen mode Exit fullscreen mode

In above products data, if you want to group data by it's type, then we can use groupBy() as shown below

Object.groupBy(products, item => item.type)
Enter fullscreen mode Exit fullscreen mode

Output:

{
  "vegetables": [
    {
      "name": "asparagus",
      "type": "vegetables",
      "quantity": 5
    }
  ],
  "fruit": [
    {
      "name": "bananas",
      "type": "fruit",
      "quantity": 0
    },
    {
      "name": "cherries",
      "type": "fruit",
      "quantity": 5
    }
  ],
  "meat": [
    {
      "name": "goat",
      "type": "meat",
      "quantity": 23
    },
    {
      "name": "fish",
      "type": "meat",
      "quantity": 22
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)