Say Hello To "Object.groupBy();"

Say Hello To "Object.groupBy();"


Hello dev mates, today I am sharing about the Object.groupBy() method which was recently introduced by Javascript, Basically what it is doing like its grouping the elements of an iterable(such as an array).

Syntax 📌

Object.groupBy(items, callbackFn)

From its syntax we know that it takes two parameters first one is items and another is a callback function.

items An iterable (such as an Array) whose elements will be grouped.

callback function It is applied to each item in the group of items. This function should provide a result that will be treated as a key (like a name or symbol) indicating which group the current item belongs to. The function is given some information when it's called, and it needs to return something that represents the category or group of the current item.

Let's understand from the examples💡

Example 1

The below code snippet showcases the implementation of the groupBy() method to organize an array of cars based on their respective models.

Within the first parameter, the array of cars is passed, and in the callback function's initial parameter, the 'model' property is destructured from each element. Subsequently, the callback function returns the model name.

In accordance with the syntax, the groupBy() method utilizes this returned model name as the key for grouping, resulting in the desired organized structure.

Various approaches exist to solve this problem, and the chosen method is considered straightforward and easy to comprehend.

Example 2

In Example 2, the objective is to group an array of students based on their ages.

The solution involves organizing the students according to their respective ages. In the code, I created the grouping keys to achieve this task.

Conclusion 🔚

Thanks for reading. I would love to hear more about your thoughts 🤩.

Happy Coding 👨🏼‍💻