3 Examples of the Underscore Reduce Function

Click to share! ⬇️

3 Examples of the Underscore Reduce Function

In Underscore, the _reduce() function is used to transform an array or object properties into one single value. The signature of the reduce function is _.reduce(list, iteratee, [memo], [context]). We can see that both memo, and context are optional parameters. If the memo parameter is not provided during function execution, then it is the first array element or object property that gets used for the seed value. The reduce function makes use of a concept called memoizerization. It’s kind of a fancy way to say it remembers values. We’ll tackle this concept in the following examples of reduce(). Let’s check it out.



Reduce Integer Array Example 1

The _reduce() function is used to create a single result from a given list of values. In example 1, we have a list of simple integer values contained in the values array. We can see that on the call to the _reduce() function, we pass in the array of values to operate on, and an anonymous iteratee function. We can see that this iteratee function itself accepts a memoizer, and a number to work it’s magic. The iteratee function makes use of memoizerization, or in other words, it is remembering the return value each time it calculates a value. The first iteration runs as it normally would, however each subsequent iteration uses the return value of the prior iteration for calculation. If you run the code, you can very clearly see how this is working. So as things start executing, the first value that’s placed into the memoizer argument by reduce is the first value within the array. So it says Calculating 1 + 2 and that returns 3. So then, 3 is placed into memoizer and so the next time it runs, this remembered value is used as the first argument. The second iteration is Calculating 3 + 3. The third is Calculating 6 + 4, and so on. So the memoizerization of reduce allows it to keep track of the last results, which is then passed back into the function. In this particular example, it’s the running total, which makes it easy to sum up the values contained in the array.

var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var sum = _.reduce(values, function (memoizer, number) {
    log('Calculating: ' + memoizer + ' + ' + number, '#reduceexampleoneunderscore');

    return memoizer + number;
});

log('All numbers equal:', '#reduceexampleoneunderscore');
log(sum, '#reduceexampleoneunderscore');

Click Clear


Reduce Object Array With Initial Value Example 2

In addition to passing in the first value of the array as the first parameter, you can also set the initial value explicitly. Example two of the _reduce() function shows us how this works. In this case, we are going to go fishing and we need some supplies. The supplies property holds an array of objects which we need for a good trip. We’ll need a fishing pole, a license to fish, gas for the boat, and some new lures for good luck. We make use of _reduce() by passing in data.supplies as the first argument, the iterator function as the second, and an integer value of 0 as the third. This forces the memoizer to begin at 0 which is important in this case of using an object array. This makes for a first iteration of 0 + 49 = 49 and then each iteration is fed the result of the prior iteration just like in the first example. Go ahead and run the code to see how much it will cost us to go fishing.

var data = {
    supplies: [
        {item: 'Ugly Stick Pole', price: 49},
        {item: 'Fishing License', price: 35},
        {item: 'Gas for boat', price: 55},
        {item: 'New Lures', price: 20}
    ]
};

var total = _.reduce(data.supplies,
        function (memoizer, value) {
            return memoizer + value.price;
        }, 0);

log('Total price to go fishing: $' + total, '#reduceexampletwounderscore');

Click Clear


Reduce Object Array With Anonymous Object Example 3

In this third example of the reduce function in Underscore, we make use of an anonymous object. In this example, we’ll hit the slopes instead of the lakes. The data structure is similar, but instead of fishing supplies, we have supplies to go skiing. The call to _reduce() is similar as well. What is different is how we set up the return statement. Instead of returning a single value, we return an object which has a key of price and a value of memoizer.price + value.price. Just like the prior example, a running tally of the prices within the array is calculated. To see the final result, we can simply access total.price, which is exactly what we do when logging out the data.

var data = {
    supplies: [
        {item: 'New Skis', price: 1200},
        {item: 'Lift Ticket', price: 75},
        {item: 'Lunch', price: 25},
        {item: 'Gas for car', price: 30}
    ]
};

var total = _.reduce(data.supplies,
        function (memoizer, value) {
            return {price: (memoizer.price + value.price)};
        });

log('Total cost to go skiing: $' + total.price, '#reduceexamplethreeunderscore');

Click Clear


3 Examples of the Underscore Reduce Function Summary

Hopefully you enjoyed these different examples of the _reduce() function in Underscore JS. Mostly, we can see that the concept of _reduce() is to take a list of values, and reduce that list down to one single value, which is exactly what we did here in this tutorial.

Click to share! ⬇️