I have a Javascript array that I would like to split into two based on whether a function called on each element returns true
or false
. Essentially
You can use reduce for it:
function partition(array, callback){
return array.reduce(function(result, element, i) {
callback(element, i, array)
? result[0].push(element)
: result[1].push(element);
return result;
}, [[],[]]
);
};
Update. Using ES6 syntax you also can do that using recursion:
function partition([current, ...tail], f, [left, right] = [[], []]) {
if(current === undefined) {
return [left, right];
}
if(f(current)) {
return partition(tail, f, [[...left, current], right]);
}
return partition(tail, f, [left, [...right, current]]);
}