DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

New Array Method in JavaScript: groupBy

The groupBy method is a new addition to the JavaScript standard library that simplifies the process of grouping elements in an array based on a specified key or function. It was officially introduced in ECMAScript 2021.

Syntax

array.groupBy(keyFn, [mapFn])
Enter fullscreen mode Exit fullscreen mode

Arguments:

  • keyFn: A function that takes an element as an argument and returns the key for grouping.
  • mapFn (Optional): A function that takes an element as an argument and returns the transformed value to store under the key.

Return value

The groupBy method returns a new Map object where the keys are the unique values of the key function application to each element, and the values are arrays containing the corresponding elements from the original array.

Examples

Example 1: Grouping by a property

const people = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Peter", age: 30 },
];

const groupedByAge = people.groupBy(person => person.age);

console.log(groupedByAge);
// {
//   30: [{ name: "John", age: 30 }, { name: "Peter", age: 30 }],
//   25: [{ name: "Jane", age: 25 }],
// }
Enter fullscreen mode Exit fullscreen mode

Example 2: Grouping and transforming elements

const products = [
  { name: "Apple", price: 1.5 },
  { name: "Banana", price: 0.8 },
  { name: "Orange", price: 1.2 },
];

const groupedByPrice = products.groupBy(
  product => product.price,
  product => product.name
);

console.log(groupedByPrice);
// {
//   "1.5": ["Apple"],
//   "0.8": ["Banana"],
//   "1.2": ["Orange"],
// }
Enter fullscreen mode Exit fullscreen mode

Advantages of using groupBy

  • Conciseness: Compared to using loops and manual manipulation, groupBy provides a more concise and readable way to achieve the same result.
  • Readability: The code becomes more readable and easier to understand, especially when dealing with complex data structures.
  • Efficiency: Depending on the implementation, groupBy can be more efficient than manual approaches, especially for large datasets.

Compatibility

The groupBy method is relatively new and not yet supported by all browsers. However, it is widely supported by modern browsers and can be easily polyfilled for older environments.

Top comments (8)

Collapse
 
efpage profile image
Eckehard • Edited

It is not rocket science to write some code to sort things in a similar way, but I can think of many other ways that "could" be useful. Here is a quick implementation that could probably made even shorter:

const people = [
    { name: "John", age: 30 },
    { name: "Jane", age: 25 },
    { name: "Peter", age: 30 },
    { name: "Harry", age: 30 },
    { name: "Bob", age: 25 },
    { name: "Jim" },
];

function GroupedByAge(arr, prop) {
    ret = {}
    arr.forEach(el => {
        let p = el[prop] + '' ?? "undefined"
        if (ret[p]) ret[p].push(el)
        else ret[p] = [el]
    })
    return ret
}

console.log(JSON.stringify(GroupedByAge(people, "age")));
Enter fullscreen mode Exit fullscreen mode

Though it is nice to have some convenience tools, we should consider if it is really worth to put anything in the JS core. Are there really so many cases people will use this? Javascript is already bloated with too many tools and concepts people need and struggle to learn.

I would prefer a language with a small but essential toolset that provides what´s necessary, not anything that´s possible. Things like this could better fit in some utility library

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Unfortunately this is not correct at all, and will not work on ANY browser (I don't think). The proposal is for Object.groupBy (and also Map.groupBy):

const people = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Peter", age: 30 },
]

const groupedByAge = Object.groupBy(people, person => person.age)
Enter fullscreen mode Exit fullscreen mode

Object.groupBy returns an object (with a null prototype), whereas Map.groupBy returns (you guessed it!) a map.

I believe Array.groupBy was dumped in favour of these because there was/is a popular existing library that implemented a groupBy method on the Array prototype, so making it native could have caused havoc.

You can read more here.

Collapse
 
manthanank profile image
Manthan Ankolekar

The groupBy method is relatively new and not yet supported by all browsers.

Checkout this: developer.mozilla.org/en-US/docs/W...

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Yes, this link shows exactly what I was talking about: Object.groupBy. It isn't a new array method

Collapse
 
gkucmierz profile image
Grzegorz Kućmierz
const tip = 'You can use "js" formatting in block codes';
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wraith profile image
Jake Lundberg

I am so happy we’re finally seeing support for this! 🎉

Collapse
 
svidlak profile image
Max Svidlo

I made a small benchmark on this, might take a look:

dev.to/svidlak/is-javascript-objec...

Collapse
 
sabbirfeni profile image
Amdad

Great