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!

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.

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 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.

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

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.

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.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

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

Hot Article

Hot Tools

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

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.
