The reduce method performs a computation that involves an initial value and every array element.  The reduce method takes two arguments: an iteration function and an initial value.  The iteration function also takes two values: the first value is the variable that will be holding the computed value and the second argument will be assigned to the array elements during iteration.  Here’s an example that runs a total of distance traveled:

var trips = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];

var totalDistance = trips.reduce(function(sum, trip){
    return sum + trip.distance;
}, 0);

console.log(totalDistance);

 

Here’s the same reduce method presented in a way that might be easier to read:

var trips = [{ distance: 34 }, { distance: 12 } , { distance: 1 }];

var iterationFunction = function(sum, trip){
    return sum + trip.distance;
};

var initialValue = 0;

var totalDistance = trips.reduce(iterationFunction, initialValue);

console.log(totalDistance);

 

Here’s an example where the result is an object, instead of a single number:

var desks = [
  { type: 'sitting' },
  { type: 'standing' },
  { type: 'sitting' },
  { type: 'sitting' },
  { type: 'standing' }
];

var deskTypes = desks.reduce(function(stats, desk) {
    if(desk.type === 'standing'){
        stats.standing++;
    } else  if(desk.type === 'sitting'){
        stats.sitting++;
    }
    return stats;
}, { sitting: 0, standing: 0 });

console.log(deskTypes);

------------------------------------------------
Console Output:
Object {
  "sitting": 3,
  "standing": 2
}

 

Here’s another example.  In this case, we are using reduce to create an array of unique values.

function unique(array) {
    return array.reduce(function(result, item){
        if(!result.includes(item)){
            result.push(item);
        }
        return result;        
    }, []);
}

var numbers = [1, 1, 2, 3, 4, 4];

console.log(unique(numbers));