partition()
The other day I wanted to filter an array into two separate arrays. I’ll make a trivial example:
const nums = [1, 2, 3, 4, 5, 6]
// The 1s and 0s are coerced into trues and falses respectively
const odds = nums.filter(n => n % 2)
const evens = nums.filter(n => !(n % 2))
From a big-O notation perspective, it’s more than likely fine to do this loop twice. It would take a rather large array to make this very problematic. That said, it’s undeniably frustrating that we can’t already get the other items from .filter()
. Hence, partition
.
I didn’t know this was in lodash
before I set out to write the function (but that’s where I got the name), so feel free to use that version instead. My version is curried for funsies. Slap the arguments together if you prefer.
const partition = predicate => array =>
array.reduce(
(acc, cur) => {
predicate(cur) ? acc[0].push(cur) : acc[1].push(cur)
return acc
},
[[], []]
)
Using reduce
, we can do a single pass through the array, calling the predicate
function for each item . As we loop through our items, we build up a tuple. The first array in the tuple are the true
s, the second, the false
s. Using our example from before:
const nums = [1, 2, 3, 4, 5, 6]
const [odds, evens] = partition(n => n % 2)(nums)
And there you have it.
Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.