How to use the reduce() in JavaScript and React

Vijay
YavarTechWorks
Published in
3 min readMar 1, 2023

Reducing a collection of values into a single value using reduce() is one of the most popular and widely used functions when working with JavaScript and React.

how to use the reduce() in JavaScript and React

When developing an application, you are asked to find the sum of all elements of an array. Now you use a for loop or the forEach(). JavaScript offers a built-in reduce() function the easiest way to do it. This blog will teach you how to use JavaScript and React reduce() functions.

What is the reduce()?

The reduce() method reduces an array to a single value by calling a callback function in every item of the existing array.

NOTE:
The reduce() does not execute the callback function for empty elements. It also doesn’t change the original array.
Usually, array element 0 is used as the initial value, and the iteration starts from array element 1. If the initial value is supplied, the iteration begins from array element 0.

Syntax

array.reduce(function(accumulator, currentValue, currentIndex, array), initialValue)

Parameters

  1. callbackFn (Required)
    A function to execute for each element in the array.
    Arguments
    accumulator
    The initial value, or the previously returned value of the function.
    currentValue (Required)
    The value of the current element.
    currentIndex (Optional)
    The index of the current element.
    array (Optional)
    The array of the current element.
  2. initialValue (Optional)
    A value is to be passed to the function as the initial value.

Return Value
The accumulated result from the last call of the callback function.

Example

const total = [90,99,70,55,23];
const sum = total.reduce(
(previousValue, currentValue, index) => previousValue + currentValue,
0);
console.log(sum); // 337

What happens in the code is:

  1. Call the reduce() on the array total.
  2. Access to the array’s previous value, current value, and index.
  3. Set the initial value of 0 as the accumulator.
  4. When the function first runs (where currentValue is 90), previousValue assumes the value of 0 as sent to the callback function.
  5. The result of the sum is 337.

reduce() in React

The reduce() is widely used in React. The most common use of a reduce() in React is to reduce value into a single value.

We will build a simple React application to display the total amount of products in the shopping cart using the reduce().

For this particular project, we will be using dummy shopping cart data which contains several key-value pairs as shown in this code.

const shoppingCart = [
{
id: 1,
product: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
qty: 1,
price: 109.95,
},
{
id: 2,
product: 'Mens Casual Premium Slim Fit T-Shirts ',
qty: 1,
price: 22.3,
},
{
id: 3,
product: 'Mens Cotton Jacket',
qty: 2,
price: 55.99,
},
{
id: 4,
product: 'Mens Casual Slim Fit',
qty: 1,
price: 15.99,
},
];

To calculate the total amount of products in the shopping cart, you can use the reduce(), like this:

  let total = shoppingCart.reduce((previousValue, currentValue) => {
return previousValue + currentValue.qty * currentValue.price;
}, 0);

Final Code.

import React from 'react';
import './style.css';

import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.bundle.min';

const shoppingCart = [
{
id: 1,
product: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops',
qty: 1,
price: 109.95,
},
{
id: 2,
product: 'Mens Casual Premium Slim Fit T-Shirts ',
qty: 1,
price: 22.3,
},
{
id: 3,
product: 'Mens Cotton Jacket',
qty: 2,
price: 55.99,
},
{
id: 4,
product: 'Mens Casual Slim Fit',
qty: 1,
price: 15.99,
},
];
export default function App() {
let total = shoppingCart.reduce((previousValue, currentValue) => {
return previousValue + currentValue.qty * currentValue.price;
}, 0);
return (
<div className="container text-center mt-3">
<h1>Shopping Cart</h1>
<h5>Total: ${total.toFixed(2)}</h5>
<button className="btn btn-primary mt-3">Checkout</button>
</div>
);
}
calculate the total amount of products in the shopping cart using reduce().

Conclusion

As you can see, reducing is easy in React. We can use for loop or the forEach() to get the same result but JavaScript offers a built-in reduce() function as we learned in this tutorial.

--

--