ESNext: Sort arrays using array.groupBy() and array.groupByToMap()

An ECMAScript Proposal that recently made it to Stage-3 is array grouping. The proposal brings us the array.groupBy() and array.groupByToMap() methods to easily group arrays.

~

💁‍♂️ Stage-3?

The Technical Committee which is concerned with the standardization of ECMAScript (i.e. TC39) has a 5 stage process in place, ranging from stage-0 to stage-4, by which it develops a new language feature.

Stage-3 is the Candidate Stage where the feature is considered complete and only critical changes will happen based on implementation experience. If all goes well the proposal will advance to Stage 4 without any changes, after which it will to become part of the ECMAScript Specification.

~

The Proposal

The proposal offers two methods:

Two methods are offered, groupBy and groupByToMap. The first returns a null-prototype object, which allows ergonomic destructuring and prevents accidental collisions with global Object properties. The second returns a regular Map instance, which allows grouping on complex key types.

With these methods you’ll be able to stop using array.reduce() — a method not everyone likes — to achieve grouping.

~

Examples

Take this array as input:

const array = [1, 2, 3, 4, 5];>

With array.groupBy you can create groups using arbitrary keys. The result is an regular JavaScript object:

array.groupBy((num, index, array) => {
  return num % 2 === 0 ? 'even': 'odd';
});
// =>  { odd: [1, 3, 5], even: [2, 4] }>

The array.groupByToMap method does the same, but it allows you to use complex types (i.e. objects) as keys. The result is a Map:

const odd  = { odd: true };
const even = { even: true };
array.groupByToMap((num, index, array) => {
  return num % 2 === 0 ? even: odd;
});
// =>  Map { {odd: true}: [1, 3, 5], {even: true}: [2, 4] }>

~

Engine Support

The methods are currently not supported in any JavaScript Engine. A polyfill is available in the core-js library.

~

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Unless noted otherwise, the contents of this post are licensed under the Creative Commons Attribution 4.0 License and code samples are licensed under the MIT License

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.