lodash _.reduce


Example

Reducing a list to a single value is easy when you have _.reduce. Let's say we wanted to see if a group of people could afford a cab ride. We'd want to look at all the money they have together as a group, which means we'd want to reduce a list of objects to a single value, in this case the sum of the money they have.

var friends = [
    {
        'name': 'Alice',
        'money': 10
    },
    {
        'name': 'Bob',
        'money': 3
    },
    {
        'name': 'Clyde',
        'money': 8
    },
]

var totalMoney = function(arr){
    return _.reduce(
        arr,
        function(accumulated, e){
            return accumulated + e.money;
        },
        0
    );
}

function canAffordCab(arr){
    return 18 < totalMoney(arr);
}

canAffordCab(friends);    // returns true