1 of 14

Array Filtering for Stage 2

(and also grouping)

2 of 14

To Recap

filter keeps items which return true

This is the opposite behavior that some users expect.

  • Completely valid to think a coffee filter acts on the liquid
  • For me, a coffee filter acts on the grounds
  • The end result is still coffee

3 of 14

Proposal is to add an “filter out” method

Would remove items which return true

  • The goal isn’t to “just make negation easier”
    • It’s easy to add a ! to any predicate, or wrap in a negate HOF
  • Instead, it’s to help with an incorrect intuition

Real Code!

4 of 14

Filtering out items

Use filterReject to reject the item

  • The fact filterReject exists helps intuition with filter
    • filterReject is the one that rejects, filter must be the one that selects

5 of 14

Array partitioning/grouping

6 of 14

Partitioning an array

Partitioning is special form of filtering

  • Collects both the selections and rejections

7 of 14

Issues with Partition

  • What order is the return value?
    • [trues, falses], or [falses, trues]?
    • Well, false == 0, so falses first?
    • Functional languages put trues first.

8 of 14

Grouping an Array

groupBy is a more generic form of partition

  • Items are grouped together into arrays
  • The returned value is used as the key to the array in output object

​

​

9 of 14

Grouping is extremely flexible

Needed to implement a stable sort in older node. We’re grouping nodes into integer keys, and sorting the keys. Concat, and voilà.

Also known as bucketing.

​

​

​

babel/babel#13021

10 of 14

What return value?

  • Ecosystem uses normal object
  • Could use prototype-less object to avoid inherited bugs
  • Could be a Map, though this would be a large divergence

11 of 14

Difference from python itertools.groupby

Python's itertools doesn't combine all groups, only sequential groups

  • Lodash/Underscore precedence is all groups
  • Do we need a new name?

12 of 14

Do we treat array holes as undefined?

  • ES6+ methods were supposed to pretend holes don't exist
    1. find treats holes as undefined
    2. flatMap skips holes

​

13 of 14

Discussion

14 of 14

Stage 2?

(Both filterRejct and groupBy)