proposal-array-filtering
proposal-array-filtering copied to clipboard
Array#filterMap
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)
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.