Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Add and Remove Items in Arrays using Filter, Reject and Partition in Ramda

    Andy Van SlaarsAndy Van Slaars

    We'll learn how to get a subset of an array by specifying items to include with filter, or items to exclude using reject. We'll also look at how to get the results from both filter and reject, neatly separated with partition.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Here I have an array of objects representing pets, three dogs and two cats. I've imported the Ramda library. I'm going to use Ramda to filter the pets array and return just the dogs.

    I'll start by defining a predicate function, which I'll call "dogcheck." Dogcheck is going to be a function that's going to take in a pet. It's going to check "pet.type," see if it's equal to "dog."

    To get my result, I'm going to call "R.filter," passing it dogcheck and the pets array. So we can see what's happening, I'm going to log out result. I can run that, and we should get a list back with just the three dogs.

    Let's say instead of the dogs, I want to get back the cats. What I could do is come up here and duplicate this. I could create "catcheck" that checks the pet's type against cat, call that as my predicate in my filter. When I run that, I'll get back the two cats rather than three dogs.

    Because I'm using Ramda, there's another way I can handle this. Let's get rid of catcheck and set this back to dogcheck. Of course, if I run this, I'm going to get the dogs, because I'm filtering based on dogcheck. What I can do, here, is I can change this filter to "reject," and I can have it reject the dogs, which will give me the cats.

    Let's say I need both dogs and cats, but I want to separate them based on this predicate. There's a way to do that, too. I can come in here, and I can say "R.partition," pass it a predicate function in my collection.

    When I run it, you'll see I get a nested array, where the first element are the items that match my predicate, so the results I would get for "filter." The second array are the results I would get for "reject."