Become a member
to unlock all features

Level Up!

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


    Calculate a sum using reduce in ImmutableJS

    Taylor BellTaylor Bell

    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.



    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




    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.