Calculate a sum using reduce in ImmutableJS

Taylor Bell
InstructorTaylor Bell
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

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.

[00:00] 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.

[00:28] 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.

[00:54] 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.

Taylor Bell
Taylor Bellinstructor
~ 8 years ago

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)

Markdown supported.
Become a member to join the discussionEnroll Today