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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
