Create a list with nested reduce functions in ImmutableJS

Taylor Bell
InstructorTaylor Bell
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 5 years ago

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.

[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.

egghead
egghead
~ 3 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today