Javascript Array Method: Reduce

Javascript Array Method: Reduce

In this post, we will dive deep into one of the most powerful methods available in JavaScript arrays: the reduce method. This method is incredibly useful for accumulating values, transforming arrays, and much more.

Basic Example of reduce

Let's start with a simple example to understand how the reduce method works. We'll use an array of numbers and sum them up.

const myNums = [1, 2, 3];
const myTotal = myNums.reduce(function (acc, currval) {
    console.log(`acc: ${acc} and currval: ${currval}`);
    return acc + currval;
}, 0);
console.log(myTotal);

//outputs:
acc: 0 and currval: 1
acc: 1 and currval: 2
acc: 3 and currval: 3
6

In this example:

  • acc is the accumulator, which accumulates the callback's return values.

  • currval is the current value being processed in the array.

  • 0 is the initial value for the accumulator & the initial value has to be passed

The reduce method iterates over each element in the array, applying the provided function, and accumulates the results. The final value of myTotal will be 6.

Arrow Function Representation

We can rewrite the above function using an arrow function for a more concise syntax:

const myNums = [1, 2, 3];

const Total = myNums.reduce((acc, currval) => acc + currval, 0);
console.log(`value of Total is ${Total}`);

// outputs:
6

This arrow function does the same thing as the previous example, summing up the numbers in the array. The output will be 6.

Real-World Example: Shopping Cart

Now, let's look at a more practical example where we use reduce to calculate the total price of items in a shopping cart.

const shoppingCart = [
    {
        itemName: "js course",
        price: 2999
    },
    {
        itemName: "py course",
        price: 999
    },
    {
        itemName: "mobile dev course",
        price: 5999
    },
    {
        itemName: "data science course",
        price: 12999
    }
];

const priceToPay = shoppingCart.reduce((acc, item) => acc + item.price, 0);
console.log(`Total: ${priceToPay}`);

//outputs:
Total: 22996