New Array Method in JavaScript: groupBy

Manthan Ankolekar - Dec 7 '23 - - Dev Community

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player