Learn 5 ways to use the JS reduce() method through examples
The reduce() method executes a reducer function (provided by you) on each element in the array, resulting in a single output value.
reduce()
method reduces all elements in an array into a single output value, which can be a number, object, or string. reduce()
The method has two parameters, the first is the callback function, and the second is the initial value.
Callback function
The callback function is executed on each element of the array. The return value of the callback function is the accumulated result and is provided as a parameter for the next call to the callback function. The callback function takes four parameters.
- Accumulator (accumulator) - The return value of the accumulator accumulation callback function.
- Current Value (current value) - Processes the current element of the array.
- Current Index (current index) - handles the index of the current element of the array.
- Source Array (source array)
Current Index
and Source Array
are optional.
Initial value
If an initial value is specified, the accumulator is set to initialValue
as the initial element. Otherwise, set the accumulator to the first element of the array as the initial element.
arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])
In the code snippet below, the first accumulator (accumulator
) is assigned an initial value of 0. currentValue
is the element of the numbersArr
array being processed. Here, currentValue
is added to the accumulator and the next time the callback function is called, the return value is provided as a parameter.
const numbersArr = [67, 90, 100, 37, 60]; const total = numbersArr.reduce(function(accumulator, currentValue){ console.log("accumulator is " + accumulator + " current value is " + currentValue); return accumulator + currentValue; }, 0); console.log("total : "+ total);
Output
accumulator is 0 current value is 67 accumulator is 67 current value is 90 accumulator is 157 current value is 100 accumulator is 257 current value is 37 accumulator is 294 current value is 60 total : 354
JavaScript reduce use case
1. Sum all values of the array
In the code below, studentResult
The array has 5 numbers. Using the reduce()
method, reduce an array to a single value that assigns all values and results of the studentResult
array to total
.
const studentResult = [67, 90, 100, 37, 60]; const total = studentResult.reduce((accumulator, currentValue) => accumulator +currentValue, 0); console.log(total); // 354
2. The sum of the values in the object array
Usually, we get the data from the backend as an object array, therefore, the reduce()
method helps in management Our front-end logic. In the code below, the studentResult
object array has three subjects, here, currentValue.marks
takes the score of each subject in the studentResult
object array.
const studentResult = [ { subject: '数学', marks: 78 }, { subject: '物理', marks: 80 }, { subject: '化学', marks: 93 } ]; const total = studentResult.reduce((accumulator, currentValue) => accumulator + currentValue.marks, 0); console.log(total); // 251
3. Flatten array
"Flat array" refers to converting a multi-dimensional array into one dimension. In the code below, the twoDArr
2-dimensional array is converted into a oneDArr
one-dimensional array. Here, the first [1,2]
array is assigned to the accumulator accumulator
, and then each remaining element of the twoDArr
array is connected to the accumulator.
const twoDArr = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ]; const oneDArr = twoDArr.reduce((accumulator, currentValue) => accumulator.concat(currentValue)); console.log(oneDArr); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
4. Group objects by attributes
According to the attributes of the object, we can use the reduce()
method to divide the object array into several groups. You can clearly understand this concept through the following code snippet. Here, the result
object array has five objects, each with subject
and marks
properties. If the score is greater than or equal to 50, the topic passes, otherwise, the topic fails.
reduce()
Used to group results into passes and failures. First, initialValue
is assigned to the accumulator, then the push()
method adds the current object to pass
and fail
after checking the condition properties as an array of objects.
const result = [ {subject: '物理', marks: 41}, {subject: '化学', marks: 59}, {subject: '高等数学', marks: 36}, {subject: '应用数学', marks: 90}, {subject: '英语', marks: 64}, ]; let initialValue = { pass: [], fail: [] } const groupedResult = result.reduce((accumulator, current) => { (current.marks >= 50) ? accumulator.pass.push(current) : accumulator.fail.push(current); return accumulator; }, initialValue); console.log(groupedResult);
Output
{ pass: [ { subject: ‘化学’, marks: 59 }, { subject: ‘应用数学’, marks: 90 }, { subject: ‘英语’, marks: 64 } ], fail: [ { subject: ‘物理’, marks: 41 }, { subject: ‘高等数学’, marks: 36 } ] }
5. Remove duplicates in array
In the following code snippet, duplicates in plicatedArr
are removed . First, an empty array is assigned to the accumulator as the initial value. accumulator.includes()
Checks whether each element of the duplicatedArr
array is already available in the accumulator. If currentValue
is not available in the accumulator, use push()
to add it.
const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7]; const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) => { if(!accumulator.includes(currentValue)){ accumulator.push(currentValue); } return accumulator; }, []); console.log(removeDuplicatedArr); // [ 1, 5, 6, 7, 8, 9 ]
Summary
In this article, we discussed the array reduce()
method. The reduce()
method is first introduced, and then its behavior is discussed using a simple example. Finally, the five most common use cases of the reduce()
method are discussed with examples. If you are a beginner in JavaScript, this article will help you.
English original address: https://medium.com/javascript-in-plain-english/5-use-cases-for-reduce-in-javascript-61ed243b8fef
Author: wathsala danthasinghe
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of Learn 5 ways to use the JS reduce() method through examples. For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use