How Can I Put The Array.reduce() Method To Use In Technical Marketing?

The Array.reduce() method is one of the most flexible ways for converting data structures in JavaScript. This article shows you how it works.

The question we’re going to be looking at today is inspired by our course, JavaScript For Digital Marketers.

In the course you mention that Array.reduce() is amazingly powerful. Can you show some examples of how it works and how it could be used for data transformations?

The Array structure is one of the most flexible and multi-purpose data structures in JavaScript.

Arrays let you store data in sequence, making it easy to use them as message queues or stacks / piles of information.

There are many ways to manipulate an array, and some of the more popular methods like .push(), .map(), and .filter(), are part of the vocabulary of many technical marketers already.

However, there is one array method that can often seem very intimidating to learn or use.

This is .reduce().

Array.reduce() iterates over all the items in the array. With each iteration, it returns a calculation of the previous iterations to the next loop. Finally, it returns a single value.

Read (or watch) on, as I’ll walk you through why this is such a useful method to know about.

Video walkthrough

If you prefer this walkthrough in video format, you can check out the video below.

Don’t forget to subscribe to the Simmer YouTube channel for more content like this.


How does Array.reduce() work?

Array.reduce() takes two arguments when called: the reducer function itself (required) as well as an initial value (optional).

The reducer iterates over every item in the array, and anything it returns will be passed to the next iteration. The initial value can be used as a starting point for these calculations on the first iteration.

See the diagram below for a visualization of the reducer.

Reducer illustration

In this case, we use the reducer to build a sum of all the items in the array. With each iteration, the current item is added to the sum of all the previous items, and this is then returned to the next iteration. The last iteration returns the total sum of all the items in the array.

Example 1: Sum of integers

We can convert the illustration above to JavaScript. The code has been made deliberately more verbose than necessary, but hopefully it is now clear how the function works with each iteration.

const arr = [2, 5, 8, 12, 15];
arr.reduce(function(total, current) {
  const totalFromPreviousIteration = total;
  const currentIterationValue = current;
  const newTotalToPassOn = totalFromPreviousIteration + currentIterationValue;
  return newTotalToPassOn;
}, 0);

In the example above, the reducer function itself has two parameters: total and current.

The first is populated by whatever was returned by the previous iteration (or the initial value if this is the first iteration), and the second is populated by the current array item.

Thus with each iteration, you can modify the value of total and return it to the next iteration.

The example above returns the value 42, which is the total sum of all the items in the array.

Example 2: Total value of the cart

Perhaps the previous example was too far removed from a real use case. I’ll show you an example you might well come across when working with digital analytics implementations, for example.

At some point, you might need to calculate the total value of the user’s shopping cart. There are many marketing pixels that want this information, and they might want it before the order is placed, in case you are measuring adds to cart or checkouts as conversion events, too.

This is what the cart in our example looks like – it could just as well be something stored in dataLayer, but in this case I’ll just use a regular JavaScript variable in the global scope.

const cart = [{
  item_id: 'SHIRTS01',
  price: 10.00,
  quantity: 2,
  category: 'clothes'
  item_id: 'PANTS02',
  price: 15.75,
  quantity: 1,
  category: 'clothes'
  item_id: 'SHOES03',
  price: 32.07,
  quantity: 3,
  category: 'shoes'

The cart is an array of objects, where each object represents one unique item. Here, price would be the price of a single item, and quantity is the number of each item currently in the cart.

If we now want to calculate the total value of this cart, we’d need to:

1. For each item in the cart, multiply price by quantity.
2. Sum all of these values together to get total cart value.

This is how we’d do it with Array.reduce():

const totalValue = cart.reduce((total, current) => {
  const currentItemValue = current.price * current.quantity;
  return total + currentItemValue;
}, 0.0);

This returns 131.96, which is the total value of all the items in the cart.

If you look at the syntax (we switched to ES6 if you’re wondering about the arrow function), it’s actually exactly the same as in the previous example. The main difference is that instead of the array containing just numbers that can be handily summed together, we need to access object properties (price and quantity) instead.

But other than that, the logic is exactly the same.

Example 3: Group and count occurrences

Here’s one final example of Array.reduce() that doesn’t involve summing stuff as in the previous two examples.

Using the cart from above, what if we want to know how many items from each category were included in the cart? This is easy to do with Array.reduce(), check it out:

const occurrences = cart.reduce((map, current) => {
  if (!map[current.category]) {
    map[current.category] = 1;
  } else {
  return map;
}, {});

This would return an object with {clothes: 2, shoes: 1}.

First, map is initialized as an empty object on line 8.

With each iteration of the cart array, the reducer checks if map already has an entry that matches the current cart item category value.

If there is an entry, then the value of that entry is incremented by 1. If there is no entry, then the entry is created with the value 1.

In this way, we can flatten a data structure in any way we like. In fact, we just converted an array into a plain object!


It took me a long while to appreciate both how Array.reduce() works and how it can be used efficiently.

Being able to iterate over an array without having to create dummy variables (I’m looking at you Array.forEach()) and without having to return an array (yes, that’s you Array.filter()) can be extremely powerful if the use case requires it.

Even though building sums and calculations are the most common ways to use a reducer, there are many scenarios where flattening more complicated data structures can be useful, especially if you need to transform the array into some other JavaScript type directly.

As with all array methods, you could reproduce what you did with Array.reduce() using a for-loop or something else, and similarly you could use Array.reduce() to replace the .filter() -> .map() combination.

Each array method has its uses, and with experience you’ll learn to pick the right tool for the right job.

Thoughts? Comment Below 👇

Your email address will not be published. Required fields are marked *

More from the Simmer Blog

The event_timestamp field in the Google Analytics 4 export to Google BigQuery is in UTC time by default. Since intraday tables are updated near realtime, it might sometimes look odd that some of your events are in the future (or too far in the past).
In this article, you'll learn how to override the user's IP address with a generic IP address from their country. This can be done with the help of a Transformation in server-side Google Tag Manager.
All Google Analytics 4 events share the timestamp of their batch. With some customization, you can add individual timestamps to (almost) all events.
Hide picture