Hi!
I'd like to propose a new Array.prototype.partition
function, following the prior art of other languages (that can be seen in the proposal repository, alongside the draft spec and polyfill).
partition
should be an utility function that returns two arrays based on the items' conformity to a predicate. Similarly to filter
, that returns an array to those items that satisfy the predicate, partition
would return two arrays - one with those items that satisfy the predicate, and one with those that don't.
const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
const isEven = (n) => n % 2 === 0;
const [even, odd] = numbers.partition(n => isEven(n));
Currently the options I see for this are either:
- doing a
.filter
twice, which is tough on performance when working with larger datasets - doing a
for
loop with conditional push - doing a
.reduce
withconcats
on the accumulator items.
One of them reads well but is not ideal, since you have to loop over twice. The other two are harder to read and reason about.
This function is already present in several languages and the usage seems intuitive enough (not attached on the name, btw, wouldn't mind changing it to something like split
or others).
This function has been present in most of the utility libraries that people, and I'm confident offering it (like includes
) in the Array prototype itself would be a nice addition.