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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

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