DEV Community

Bogdan Varlamov
Bogdan Varlamov

Posted on • Edited on

JavaScript Array Methods: Understanding `reduce`

Image description

The reduce method in JavaScript can seem a bit more complex than map and forEach. This is because it does more than just iterate over every item in an array; it accumulates values into a single element and returns this element.

Let's examine a straightforward example:

const numbers = [1, 2, 4, 5, 6]

const sum = numbers.reduce((acc, number) => {
  return (acc += number)
}, 0)

console.log(sum) // 18
Enter fullscreen mode Exit fullscreen mode

In this example, we have an array of numbers, and we calculate the sum of all these numbers using the reduce method.

How It Works

The reduce method accepts two parameters: the first is a callback function (required), and the second is the initial value for the accumulator (acc). The second argument is optional; if it's omitted, the first element of the array becomes the initial value of acc.

The callback function can perform various tasks, including setting conditions.

The key feature of the reduce function is to return a single value from the array, not an array itself.

Practical Application

Imagine a scenario where we receive an array of products that a user has selected in their online basket. Each item is stored as an object with name, price, and amount properties.

To display the total number of items in the user's basket, we can utilize reduce:

const basket = [
  { name: 'milk', price: 6, amount: 4 },
  { name: 'eggs', price: 7, amount: 2 },
  { name: 'juice', price: 4, amount: 1 },
  { name: 'chicken', price: 10, amount: 2 },
]

const itemsInBasket = basket.reduce((total, product) => {
  return (total += product.amount)
}, 0)

console.log(itemsInBasket) // 9
Enter fullscreen mode Exit fullscreen mode

This practical use of reduce showcases its ability to compile information from an array into a single, comprehensive value, demonstrating its utility in real-world applications, such as calculating totals in a shopping basket.

Thanks for hanging out! Hit subscribe for more! 👋

Top comments (0)