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 =>
    (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.

Let's talk some more about JavaScript, React, and software engineering.

I write a newsletter to share my thoughts and the projects I'm working on. I would love for you to join the conversation. You can unsubscribe at any time.

Data Structures and Algorithms Logo
Data Structures and Algorithms

Check out my courses!

Liked the post? You might like my video courses, too. Click the button to view this course or go to Courses for more information.
View on