 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
1×
Become a member
to unlock all features Level Up!

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

Autoplay

Calculate a sum using reduce in ImmutableJS Immutable.js

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. 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 Discuss Transcript

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 0since 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 0for our initial value.