Array reduce method in JS

Array reduce method in JS

Level up your programming skills by harnessing the power of array.reduce()

In simple words, the array reduce method is used to reduce an array into a single value, after performing some operations on its elements. The value can be a string, number, boolean, object, array, or any other custom data type, depending on how the callback function is implemented.

Syntax: arr.reduce(callbackFn, initialValue)

It accepts two arguments, a callback function and an initial value (which is optional by the way).

The callback function accepts 4 arguments:

  1. accumulator: It keeps track of the intermediate result as the reduce operation progresses. It starts with the value of the initialValue if provided, or the first element of the array if no initialValue is given.

  2. currentValue: This is the current element being processed in the array during the iteration.

  3. currentIndex: This is the index of the current element being processed. It is an optional property.

  4. array: It is the original array upon which the reduce is being called. It is an optional property.

Let's understand the concept of reduce with an example of a sneaker cart. Consider the following dataset for a sneaker cart:

const sneakers = [
  {
    brand: "Nike",
    type: "Running",
    color: "Black",
    discounted: true,
    price: 100,
    name: "Air Zoom",
  },
  {
    brand: "Adidas",
    type: "Casual",
    color: "White",
    discounted: false,
    price: 80,
    name: "Superstar",
  },
  {
    brand: "Nike",
    type: "Basketball",
    color: "Red",
    discounted: true,
    price: 120,
    name: "LeBron 18",
  },
  {
    brand: "Reebok",
    type: "Training",
    color: "Blue",
    discounted: true,
    price: 90,
    name: "Nano X",
  },
];
  • Say we want to count the number of sneakers per brand:
const brandCounts = sneakers.reduce((counts, sneaker) => {
  counts[sneaker.brand] = (counts[sneaker.brand] || 0) + 1;
  return counts;
}, {});
// OUTPUT: { Nike: 2, Adidas: 1, Reebok: 1 }

In the above example, counts is our accumulator and sneaker is our currentValue. The initial value for our accumulator is an empty object {}.

Initially, the accumulator (counts) is an empty object, in the first iteration of the loop we add a key of brand name, which we get from sneaker.brand, to the accumulator and check if the key already exists in the object; if it does, then the count is increased by 1. If it doesn't exist, a new property with the brand name is created, and its value is set to 1. This way, the brandCounts object keeps track of how many sneakers are from each brand in the sneakers array.

This operation is performed on every element of the array and each time we return the updated value of our accumulator (return counts;) and we get our final output as { Nike: 2, Adidas: 1, Reebok: 1 }.

  • Now if we want to get the total price of the cart:
const totalCost = sneakers.reduce((total, sneaker) => {
  return total + sneaker.price;
}, 0);
// OUTPUT: 390
  • What if we want to get a list of the names of all the sneakers in the cart:
const sneakerNames = sneakers.reduce((names, sneaker) => {
  names.push(sneaker.name);
  return names;
}, []);
// OUTPUT: ["Air Zoom", "Superstar", "LeBron 18", "Nano X"]

Now to practice your newly acquired skill try to use the array reduce method to return the list of sneakers that are discounted.

With this, we conclude this article on the array.reduce() method. I hope you now have a better grasp of how to harness its power for performing cumulative operations on arrays. Whether you're calculating totals, counting occurrences, or aggregating data, array.reduce() proves to be an invaluable tool in your programming arsenal. Stay tuned for more informative content, as we'll continue exploring other exciting JavaScript concepts in the next article. Until then, happy coding and keep honing your skills!