- Notifications
You must be signed in to change notification settings - Fork17
A proposal to make grouping of array items easier
License
tc39/proposal-array-grouping
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Note: this proposal is nowat stage 4. See the spec PR here:tc39/ecma262#3176
A proposal to make grouping of items in an array (and iterables) easier.
constarray=[1,2,3,4,5];// `Object.groupBy` groups items by arbitrary key.// In this case, we're grouping by even/odd keysObject.groupBy(array,(num,index)=>{returnnum%2===0 ?'even':'odd';});// => { odd: [1, 3, 5], even: [2, 4] }// `Map.groupBy` returns items in a Map, and is useful for grouping// using an object key.constodd={odd:true};consteven={even:true};Map.groupBy(array,(num,index)=>{returnnum%2===0 ?even:odd;});// => Map { {odd: true}: [1, 3, 5], {even: true}: [2, 4] }
- Justin Ridgewell (@jridgewell)
- Jordan Harband (@ljharb)
CurrentStage: 4
Array grouping is an extremely common operation, best exemplified bySQL'sGROUP BY clause and MapReduce programming (which is betterthought of map-group-reduce). The ability to combine like data intogroups allows developers to compute higher order datasets, like theaverage age of a cohort or daily LCP values for a webpage.
Two methods are offered,Object.groupBy andMap.groupBy. The firstreturns a null-prototype object, which allows ergonomic destructuringand prevents accidental collisions with global Object properties. Thesecond returns a regularMap instance, which allows grouping oncomplex key types (imagine a compound key ortuple).
We'vefound a web compatibility issue with the nameArray.prototype.groupBy. TheSugar library until v1.4.0conditionally monkey-patchesArray.prototype with an incompatiblemethod. By providing a nativegroupBy, these versions of Sugar wouldfail to install their implementation, and any sites that depend on theirbehavior would break. We've found some 660 origins that use theseversions of the Sugar library.
We then attempted the nameArray.prototype.group, but this ran intocode that uses an array as an arbitrary hashmap. Becausethese bugs are exceptionally difficult to detect (it requires devs todetect and know how to report the bug to us), the committee didn't wantto attempt another prototype method name. Instead we chose to use staticmethod, which we believe is unorthodox enough to not risk a webcompatibility issue. This also gives us a nice way to support Recordsand Tuples in the future.
- A polyfill is available in thecore-js library. You can find it intheECMAScript proposals section.
- Lodash
About
A proposal to make grouping of array items easier
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.
Contributors10
Uh oh!
There was an error while loading.Please reload this page.