DEV Community

Vivek Kumar
Vivek Kumar

Posted on

1 1

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay