Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 832 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Just one more step!

Check your inbox for an email from us and click link to unlock your lesson.



Calculate a sum using reduce in ImmutableJS

1:22 JavaScript lesson by

The reduce function in ImmutableJS allows you to transform and create new data from an existing data structure. In this example, we will do some math and calculate a sum based on data in an ImmutableJS Map.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

The reduce function in ImmutableJS allows you to transform and create new data from an existing data structure. In this example, we will do some math and calculate a sum based on data in an ImmutableJS Map.

Avatar
Taylor Bell

In this example, I'm returning an assignment with += :

const subtotal = cart.get('items').reduce((t, i) => t += i.get('price'), 0)

This code works, but it's not necessary to do the assignment, since the sum is what I actually want:
const subtotal = cart.get('items').reduce((t, i) => t + i.get('price'), 0)

We have an immutable map representing a cart, and I want to calculate the subtotal of its items. We'll do this by writing const subtotal = cart.getItems.reduce(). Reduce takes two parameters, the first is a callback function that can take four parameters, a previous value, current value, index, and the full original item, in this case our cart. The second parameter to reduce is our initial value, which we'll make 0 since we're calculating a total.

In order to see what's going on inside of our callback, let's start by logging prev, then logging the current index and the price of our current item, which we can find with curr.getPrice(). To calculate our subtotal, we'll add prev and our current price. On our second iteration, notice that our subtotal is not a number. That's' because we need to return the sum of previous and our current item's price.

We don't have to supply arguments to our callback function that we aren't going to use, so we can write this reduce function in just one line, subtotal = cart.getItems.reduce(t, i). Remember, when we use curly braces that we don't have to use the return keyword, so we can just do t+= i.getPrice(), and then 0 for our initial value.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?