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?

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


Are you, or the company you work for, struggling with something mentioned in this article?
Would you benefit from a live training session?
Let's Talk
Kyle Shevlin's face, which is mostly a beard with eyes
Kyle Shevlin is a software engineer who specializes in JavaScript, TypeScript, React and frontend web development.

Let's talk some more about JavaScript, TypeScript, 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.

Array.reduce() Logo
Array.reduce()

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.
View the course
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-fiorinimedayzTowardsDeathFanchGadjonoahmateenbrandonpittman
©2023 Kyle Shevlin. All Rights Reserved.