proposal-array-filtering icon indicating copy to clipboard operation
proposal-array-filtering copied to clipboard

Array#filterMap

Open lukescott opened this issue 5 years ago • 2 comments

With flatMap added with flat to reduce iterations and allocations, it would be nice to have an accompanying filterMap method as well. I often find filter and map used together.

Something like this:

[{active: true, label: "foo"}, {active: true, label: "bar"}]
  .filter(v => v.active)
  .map(v => v.label)

Could be written as:

[{active: true, label: "foo"}, {active: true, label: "bar"}]
  .filterMap(v => v.active && v.label)

lukescott avatar Feb 27 '20 21:02 lukescott

This is actually possible via flatMap:

array.flatMap(v => {
  if (!v.active) {
    // Returning an empty array here is equivalent to filtering out the element.
    return [];
  }

  // Returning a single element array with the mapped value keeps the element.
  return [v.label];
});

Exposing an API like this would have to deal with choosing a value that represents "filter this out". Is it false? What if I wanted to map to boolean values?

flatMap's wrapping arrays sidestep this, since it's not the return value but the value's length that differentiates it.

jridgewell avatar Feb 27 '20 21:02 jridgewell