search
HomeWeb Front-endJS TutorialUnderstanding Array.reduce()

Understanding Array.reduce()

Introduction

While taking a introduction course on Javascript and learning about all of the different methods of the Arrays. I did not quite understand the real power of the reduce method and it is only after going back to it a second time that I am now realising how truly useful this method is. I hope the article might make it clearer for some about how this method works and when to use it.

The Method

Array.prototype.reduce(callbackFunction)
Array.prototype.reduce(callbackFunction, initialValue)

What exactly does this method do?

The reduce() method processes each element of an array using a callback function, accumulating the result into a single value. If an initial value is provided, it's used as the starting point; otherwise, the first array element is used, and the iteration starts from the second element.

Callback Function Parameters

callbackFunction(accumulator, currentValue, currentIndex, array){}

accumulator

The accumulated result from the previous iteration or the initial value if provided.

currentValue

The value of the current array element being processed.

currentIndex

The index of the current element, starting at 0 if an initial value is provided, otherwise 1.

array

The array on which the reduce() method is being executed.

Initial Value

When using the reduce method without a initial value, the callback function will take the first element of the array and initialize it as the accumulator and then iterate through the rest of the array.

Use cases

The most common example you will encounter using the reduce method is the sum of an array.

const ages = [23, 15, 45, 13, 66, 54, 38];
let sumOfAges = ages.reduce(function(sumOfAges, currentAge){
    sumOfAges = sumOfAges + currentAge;
    return sumOfAges;
}); // 254

While yes this is exactly what the reduce method is good for and good at, there is a lot more it can do.

Getting the max age of a group

const ages = [23, 15, 45, 13, 66, 54, 38];
let oldestPerson = ages.reduce(function(maxAge, currentAge){
    if(currentAge>maxAge){
        maxAge = currentAge;
    }
    return maxAge;
}); // 66

Here we are using the reduce method to save the highest age that we are encountering in the array and returning that value once iterated through the whole array.

Removing Duplicates in a Array

const store = ['apple', 'pear', 'apple', 'orange', 'apple', 'pear'];
let itemCatalogue = store.reduce(function(uniqueStoreItems, currentItem){
    if(!uniqueStoreItems.includes(currentItem)){
        uniqueStoreItems.push(currentItem);
    }
    return uniqueStoreItems;
}, []); // ['apple', 'pear', 'orange']

Important to note here that for the initial value in the reduce method we are supplying an empty array, []. This means that the accumulator is now an array, and our call back function pushes only items that are not already in that array. As a result we have removed duplicates.

Getting a Count of Items in a Array

const store = ['apple', 'pear', 'apple', 'orange', 'apple', 'pear'];
let itemCount = store.reduce(function(count, currentItem){
    count[currentItem] = (count[currentItem] || 0) + 1;
    return count;
}, {}); // { apple: 3, pear: 2, orange: 1 }

Important to note here is that the initial value is an empty object. As we go through the items in the store, we populate the item with the count.

Conclusion

First of all if you've made it this far thanks for the read! My main goal for writing this article was for me to solidify my understanding of the reduce method and I hope that maybe you learned something new here too! The reduce method has a lot of really cool applications and is really neat to use. Have you got any other use cases or fun tricks with the method? I would love to know!

The above is the detailed content of Understanding Array.reduce(). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)