jgozal jgozal - 2 months ago 6
Javascript Question

first object of array not being passed into initialValue parameter in reduce()

This is my code:

var deliveries = [
{
"id": 1,
"destination": 'Oakland',
"orderPrice": 75,
"rushDelivery": true,
"rushDeliveryFee": 12.75,
"orderDate": "4 April 2016"
},
{
"id": 2,
"destination": 'San Jose',
"orderPrice": 62.75,
"orderDate": "5 April 2016"
},
{
"id": 3,
"destination": 'San Francisco',
"orderPrice": 15.00,
"rushDelivery": true,
"rushDeliveryFee": 50.75,
"orderDate": "10 April 2016"
},
{
"id": 4,
"destination": 'San Francisco',
"orderPrice": 25,
"orderDate": "4/11/2016"
},
{
"id": 5,
"destination": 'San Francisco',
"orderPrice": 90,
"rushDelivery": true,
"rushDeliveryFee": 30,
"orderDate": "April 12, 2015"
},
{
"id": 6,
"destination": 'Berkeley',
"orderPrice": 45,
"orderDate": "4/01/2015"
},
{
"id": 7,
"destination": 'Berkeley',
"orderPrice": 62.16,
"orderDate": "12 April 2016"
}
];


var orderPrices = deliveries.reduce(function(prev, current) {
return prev.orderPrice + current.orderPrice
})

console.log(orderPrices);


When I
console.log
prev.orderPrice
in the first iteration of
reduce()
it prints
undefined
, but from what I understand, if you give no second argument(the
initialValue
) to
reduce()
, it simply defaults to the first element of the array to which you apply the function to. I would expect the first object of the array to be printed. In fact, if we try this with another simpler array like
var arr = [1,2,3,4,5]
,
prev
prints 1 in the first iteration.

Why is this happening?

Answer

The elements in array are reduced 1 by 1 from left to right. Thus, from the second iteration, the prev argument is the current total value already:

    var orderPrices = deliveries.reduce(function (prev, current) {
        if (prev.orderPrice)
        {
            return prev.orderPrice + current.orderPrice;
        }
        return prev + current.orderPrice;
    });

    console.log(orderPrices);