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

Already subscribed? Sign In

Autoplay

    Create a list with nested reduce functions in ImmutableJS

    Taylor BellTaylor Bell

    ImmutableJS reduce functions can be nested to get data out of complex data structures. In this example, we will create an Immutable List from an Immutable Map that is nested inside of an Immutable List that is itself nested inside of an Immutable Map.

    immutableImmutable.js
    Code

    Code

    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
    Transcript

    Transcript

    00:00 We have an Immutable map representing a cart with a couple of albums in it, and I want to make an Immutable list of all the performers.

    00:06 We'll start by writing const names = cart.getItems.reduce. Our first argument is the callback function, which we'll give P for previous and C for current, and our initial value with be an empty Immutable list.

    00:20 Inside our reduce function, we can console.log C, which shows us each item in our cart. Notice that Personnel is an Immutable list that contains an Immutable map for each of the featured performers.

    00:30 In order to process the Personnel list, we will reduce over our personnel. The setup is similar to what we've done on the outer reduce. We'll create a constant, N, and we'll set it equal to C.getPersonnel.reduce.

    00:42 When I nest reduce functions, I like to add an I to my previous and current variables, since they're inside. I'll put PI for previous inside and CI for current inside. This also allows us to maintain access to our P variable from the outer reduce in case it's needed.

    00:57 Since we're making a list, our initial value for our inner reduce will again me an Immutable list. If we console.log CI, we see a map for each performer. Since we want to make a list of the performers' names, we'll return PI.concat CI.getName.

    01:13 Now, in our outer reduce, we'll return P.concat N, which is the list of names created by the inner reduce. Now, when we console.log names, we'll see our list of names in the order they were added to the list.

    01:26 I think it would look better sorted, so let's put a .sort on it.

    Discuss

    Discuss