Snippet

partition()

edit

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 trues, the second, the falses. 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.


Liked the post?
Give the author a dopamine boost with a few "beard strokes". Click the beard up to 50 times to show your appreciation.

Kyle Shevlin's face, which is mostly a beard with eyes

Kyle Shevlin is the founder & lead software engineer of Agathist, a software development firm with a mission to build good software with good people.

Logo for Just Enough Functional Programming
Just Enough Functional Programming
Check out my courses!
If you enjoy my posts, you might enjoy my courses, too. Click the button to view the course or go to Courses for more information.
Sign up for my newsletter
Let's chat some more about TypeScript, React, and frontend web development. Unsubscribe at any time.