Currently there is no way to partition an array into multiple parts based on a callback function, without calling filter
multiple times.
const callback = (item) => someCondition;
const matchingItems = arrayToPartition(callback);
const nonMatchingItems = arrayToPartition(item => !callback(item));
This approach has the downside of iterating over the array multiple times.
An alternate solution is to manually iterate over the array:
const callback = (item) => someCondition;
const matchingItems = [];
const nonMatchingItems = [];
for (const item of arrayToPartition) {
if (callback(item)) {
matchingItems.push(item);
} else {
nonMatchingItems.push(item);
}
}
This approach is efficient, but requires a lot of code.
We propose the addition of a new method to the Array prototype - partition
. This would give developers a straight-forward way to accomplish this common, basic operation.
const callback = (item) => someCondition;
const [nonMatchingItems, matchingItems] = arrayToPartition.partition(callback);
This could potentially be extended so that callback can also return any integer >= 0, which would then partition that item into an array matching that index in the return value. In this case you could still return a boolean value where false = 0, true = 1 and thus the return value is consistent.
The proposed signature is the same as the existing Array.prototype.filter
method:
Array.prototype.partition(callback[, thisArg])
A simplified API
TODO
- Polyfills: TODO (but trivial)