Reducers in JavaScript Arrays

Today, I decided to build a Vuex shopping cart and ran into reduces. I had no idea how this worked 5 mins prior to me writing this blog post .

What the reducer does is return a single value from an array in any data type, whether it’s a sting, boolean, number, etc. In the example below we have an array and a high order function.

const numbers = [1,2,3,4,5,3,2,1]const reducer = (acc, val) => acc + valconsole.log(numbers.reduce(reducer) )

This is straight from the Mozilla docs but I felt that the explanation is quite vague for beginners.

What the reducer variable is doing is taking the accumulator as a starting point for the total value being return. If you’re familiar with For Loops this is very similar to how you would create a starting variable to keep track of the total value as the loop iterates over your array. For example, “let sum = 0”. Check out the video below to see how the reduce method is compared to a for loop.

https://www.youtube.com/watch?v=g1C40tDP0Bk

The “reduce” method takes a function only. The function you insert as an argument will return the final value that the array will be simplified to.

Here is my practical version of using the reducer method.

const cartItems = [
{
name:'Brush',
price:1
},
{
name:'Brush',
price:5
},

]
const reducer = (acc, currentValue) => acc + currentValue.priceconsole.log( `Your total is $${cartItems.reduce(reducer, 0)}.00`)

When using objects, be sure to give your accumulator an initial value by adding a number (usually 0) as a starting point so that your objects will return the specified data passed in, which in this case is the price of each cart item.

cartItems.reduce(reducer, 0)

As a final explanation, the Reducer function will add all of the elements in the numbers variable and then the array, using the reduce method to return the total of all the numbers into a single value.

There you have it! Now you can start reducing those arrays my friend

Software Engineer | Agency Founder | Technical Writer