1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
7

JavaScript Array reduce()

Updated on 06/08/2024359 Views

When I first started learning the JavaScript array reduce method, it looked a bit intimidating. All those terms like "accumulator" and "callback function" had me scratching my head. However, I was determined to crack it because all the other JS developers kept talking about how powerful it was for handling arrays.

After a few basic examples, things started clicking. I realized that reduce was a very handle tool for handling data. Need to sum up a bunch of numbers? Want to find the most frequent word in a piece of text? reduce could usually handle it. 

Learning its ins and outs has definitely improved how I write code that manipulates arrays. Let us learn all about JavaScript array reduce.

What is JavaScript Array reduce?

The reduce() method in JavaScript is like a powerful machine that takes an array, processes it according to your instructions, and then condenses the entire thing into a single output value. This output can be a number, a string, an object, or even a new array.

While at first reduce() can seem a bit abstract, learning it opens up a new way to approach array manipulation problems. In simple terms, think of it as a way to "boil down" a whole array of ingredients into a single, flavorful dish. 

Why Learn JavaScript Array reduce()?

Here's why mastering reduce() is a valuable addition to your JavaScript toolkit:

  • Summing, finding maximums, and more: Need to calculate the total of a bunch of numbers? Want to find the highest or lowest value in an array? reduce() streamlines these common tasks.
  • Complex transformations: reduce() goes far beyond simple calculations. You can:
    • Group elements of an array based on certain criteria.
    • Flatten nested arrays (arrays within arrays) into a single array.
    • Build up complex objects from the data in your array.
  • Clean and expressive Code: Often, reduce() lets you replace bulky loops and multiple variables with a more concise and declarative style of programming.

How JavaScript Array reduce Works

At its core, the reduce() method needs a few key ingredients:

The Array: This is the data set you'll be working with.

The Reducer Function: A function you'll define, dictating how each element of the array is processed.

initialValue: A starting point for the process.

Breaking Down the Arguments

Your reducer function will receive four arguments within each call as reduce() marches through your array:

  • accumulator: The value being built up as the process continues. It starts as the initialValue (if provided), or the first element of your array.
  • currentValue: The current element being processed in the array.
  • index: The current element's index (position) within the array.
  • initialValue: The (optional) starting value passed to reduce().

Step-by-Step Illustration

Let's say you have an array [1, 2, 3, 4] and want to calculate the sum:

  • Iteration 1:
    • accumulator: Starts as your initialValue (if provided) or the first element (1)
    • currentValue: The second element (2)
    • index: 1
  • Iteration 2:
    • accumulator: The result of the previous iteration (e.g., 3 if no initialValue)
    • currentValue: The third element (3)
    • index: 2 ... and so on until the array is fully processed

The Reducer Function

This function determines how reduce() combines the currentValue with the accumulator. The value you return from your reducer function becomes the accumulator for the next iteration. This is why the final return value of reduce() can be anything. You mold the final output in your reducer function.

Common Use Cases of JavaScript Array reduce

Let us check out some common use cases of the array reduce method in JavaScript with the help of examples.

1. Summing an Array of Numbers

Code:

const numbers = [5, 2, 8, 1];

const total = numbers.reduce((accumulator, number) => accumulator + number, 0); 

console.log(total); // Output: 16

In the above JavaScript array reduce sum example, we start with an initialValue of 0. In each iteration, we add the currentValue to the accumulator.

2. Finding Maximum/Minimum Values

Code:

const numbers = [5, 2, 8, 1];

const max = numbers.reduce((accumulator, number) => {

    return number > accumulator ? number : accumulator;

}, -Infinity); // Start with a very low initialValue for max

console.log(max); // Output: 8

Using reduce like here in this array reduce JavaScript example can make your code more readable than a traditional for loop with an if statement to track the highest value.

3. Calculating Averages

Code:

const numbers = [5, 2, 8, 1];

const average = numbers.reduce((accumulator, number, index, array) => {

    accumulator += number;

    return index === array.length - 1 ? accumulator / array.length : accumulator;

}, 0); 

console.log(average); // Output: 4

In the above example, we divide the sum by the array length after the last iteration.

4. Counting Occurrences

Code:

const words = ['apple', 'banana', 'apple', 'orange'];

const wordCounts = words.reduce((accumulator, word) => {

     if (word in accumulator) {

        accumulator[word]++;

     } else {

        accumulator[word] = 1;

     } 

     return accumulator;

}, {});

console.log(wordCounts); // Output: { apple: 2, banana: 1, orange: 1 }

In this reduce array JavaScript example, the accumulator is an object tracking how often each word appears.

If you wish to master JavaScript, you can check out upGrad’s full stack development courses.

More Complex Transformations

1. Chaining Array Methods with reduce()

JavaScript array reduce() works beautifully with other array methods like filter, map, and more. Here is an example of calculating the sum of only even numbers in an array:

Code:

const numbers = [1, 2, 5, 8];

const sumOfEven = numbers.filter(number => number % 2 === 0)

                        .reduce((sum, num) => sum + num, 0);

console.log(sumOfEven); // Output: 10

2. Grouping Objects in an Array by Property

Let's say we have an array of products and we wanted to group them. This is how we would reduce array of objects JavaScript:

Code:

const products = [

    { name: 'apple', category: 'fruit' },

    { name: 'carrot', category: 'vegetable' },

    { name: 'banana', category: 'fruit' }

];

const groupedProducts = products.reduce((accumulator, product) => {

    const key = product.category;

    if (!accumulator[key]) {

        accumulator[key] = [];

    }

    accumulator[key].push(product);

    return accumulator;

}, {});

console.log(groupedProducts); 

// Output: { fruit: [...], vegetable: [...] }

3. Flattening an Array of Arrays

Here is an example of how we can flatten an array of arrays with JS array reduce:

Code:

const nestedArray = [[1, 2], [3, 4, 5], [6]];

const flatArray = nestedArray.reduce((accumulator, subArray) => {

    return accumulator.concat(subArray);

}, []); 

console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]

Practical Examples

Let us check out some practical examples of the JavaScript array reduce method.

1. Analyzing Sales Data

Let's say we have sales data like this:

    { product: 'shirt', price: 20, quantity: 3 },

    { product: 'pants', price: 40, quantity: 1 },

    { product: 'shoes', price: 70, quantity: 2 },    

];

From the above data, we can fetch the following with the .reduce() method:

  1. Total revenue:

const totalRevenue = salesData.reduce((sum, item) => 

    sum + (item.price * item.quantity), 0);

  1. Average order value:

const averageOrder = salesData.reduce((sum, item) => 

    sum + (item.price * item.quantity), 0)  / salesData.length; 

  1. Product ranking (bestsellers):

const productRankings = salesData.reduce((rankings, item) => {

    if (rankings[item.product]) {

        rankings[item.product] += item.quantity;

    } else {

        rankings[item.product] = item.quantity;

    }

    return rankings;

}, {}); 

// Then maybe sort this object to get your top sellers

2. Word Puzzles

1. Counting Letter Frequency: 

const text = "hello world";

 const letterCounts = text.split('').reduce((accumulator, letter) => {

    // ... (Same logic as the word counting example)

 }, {});

2. Anagram Detection: Sort letters in words alphabetically, use reduce to group anagrams together.

3. Shopping Cart

For sub total:

const cartItems = [ /* ... */ ]; // Assume your cart data

const subtotal = cartItems.reduce((sum, item) => 

    sum + (item.price * item.quantity), 0);

BEst Practices for JavaScript Array reduce

I believe it is really important to talk about refining our reduce() usage for both readability and, in some cases, performance. Let’s explore some best practices.

When to (and Not to) Use reduce()

  1. Embrace its power: reduce excels when iterating over an array with the goal of producing a single value. This includes sums, averages, grouping, and more.
  2. Readability first: If a simple for loop or a different array method makes your code easier to understand, especially for beginners, then that's often the better choice. Don't sacrifice clarity for the sake of using reduce.
  3. Know your intent: If you find yourself with a very convoluted reducer function, it might be a sign that reduce isn't the best fit in that instance.

Performance Considerations

  1. Large arrays: While reduce is generally performant, on extremely large arrays, it might incur some overhead compared to an explicit loop in certain cases.
  2. Premature optimization: Profile your code if you have a true performance bottleneck. Don't sacrifice readability based on assumptions about reduce. Modern JavaScript engines are highly optimized.

Exploring Other Array Methods

  1. reduce is a Teamplayer. We can combine it with:
  • filter: Process subsets before reducing.
  • map: Transform elements before reducing them.
  • forEach: For simple actions with side effects (though less 'functional' in style).

Wrapping Up

The JavaScript array reduce method is extremely helpful at times. reduce, along with its companions map and filter, lets you write code that expresses what you want to do, rather than step-by-step how to do it.

However, we must remember one thing. reduce() is a powerful tool, but not the only tool. We should always learn to recognize when its expressive nature aligns with the problem we are solving. That being said, I cannot help myself in utilizing the JavaScript array reduce method’s power to solve so many array problems gracefully.

If you wish to master software engineering concepts such as JS array reduce, you can enroll in upGrad’s software engineering courses.

Frequently Asked Questions

  1. What does reduce() do in JavaScript?

It iterates over an array, applying a provided callback function to each element, ultimately condensing the array into a single output value.

  1. What is reduce function in JavaScript using arrow function?

Example of JavaScript array reduce arrow function: const total = numbers.reduce((accumulator, number) => accumulator + number, 0);

  1. What does => mean in JS?

The => defines an arrow function, a more concise way to write functions in JavaScript.

  1. What is a arrow function in JavaScript?

A shorthand way of writing functions, offering implicit returns and a different way of handling the this keyword compared to regular functions.

  1. What does reduce() return?

The reduce() method returns whatever value is accumulated within your callback function. This can be a number, string, object, array, etc.

  1. What is the reduce function of array?

The .reduce() method is a built-in array method in JavaScript. It performs its reduce operation on the array it's called on.

  1. How to reduce array to object in JavaScript?

You'd use reduce() with a callback function that gradually builds up the object, adding properties based on array elements.

  1. How do I reduce the size of an array?

Technically, reduce() is for transforming, not changing array size. To remove elements, you'd use methods like filter(), slice(), or splice().

  1. How do you reduce an array problem?
  • Understand reduce(): Learn its parameters and how the callback function works.
  • Problem breakdown: Think about what your single output value should be.
  • Gradual transformation: Design your callback function to work on one element at a time, contributing to the final result.
image

Pavan Vadapalli

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...