Group Array elements using the Object.groupBy method in JavaScript.

Javascript Jeep🚙💨
3 min readAug 24, 2024

Introduction

The Object.groupBy method lets you group items in an array into an object, based on a specific rule. This rule is set by a function that provides a key for each item. The method groups all items with the same key into arrays, with each key becoming a property in the object.

Syntax and Explanation

The syntax of the Object.groupBy method is straightforward:

Object.groupBy(iterableObject, callback);
  • iterableObject: An iterable objects(such as an Array) whose elements you want to group.
  • callback: A function that takes each element of the array and returns a key. The elements that produce the same key are grouped together.
  • The returned key can be a string or symbol, other returned values are converted to string.

Here’s a breakdown of how it works:

  1. The callback function is applied to each element of the array.
  2. The return value of the callback function is used as a key.
  3. The elements that share the same key are grouped into an array.
  4. The result is an object where each key corresponds to an array of grouped elements.

--

--