Kyle Shevlin

Software Engineer

Snippet

partition()

edit
0 strokes bestowed

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.


Finished reading?

Here are a few options for what to do next.

Like
Liked the post? Click the beard up to 50 times to show it
Share
Sharing this post on Twitter & elsewhere is a great way to help me out

Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, React and front end web development.

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 courses, too. Click the button to view this course or go to Courses for more information.
I would like give thanks to those who have contributed fixes and updates to this blog. If you see something that needs some love, you can join them. This blog is open sourced at https://github.com/kyleshevlin/blog
alexloudenjacobwsmithbryndymentJacobMGEvanseclectic-codingjhsukgcreativeerikvorhesHaroenvmarktnoonandependabotmarcuslyonsbrentmclarkfederico-fiorinimedayzDoNormalFanchGadjonoahmateenbrandonpittman
©2022 Kyle Shevlin. All Rights Reserved.