JavaScript array reduce() method usage example
[Related recommendations: javascript video tutorial, web front-end】
Preface
Please let me introduce this method in detail today, I hope it will be helpful to you.
This is the basic usage of reduce:
var arr = [1, 2, 3]; function reducer(parmar1, parmar2){ } arr.reduce(reducer)
reduce is a method on the array prototype object that can help us operate the array. It takes another function as its argument, which can be called a reducer.
reducer has two parameters. The first parameter param1 is the result of the last reducer run. If this is the first time the reducer is run, the default value of param1 is the value of the first element of the array.
The reduce method loops through each element in the array, just like in a for loop. And pass the current value in the loop as parameter 2.
After traversing the array, reduce will return the result calculated by the last reducer.
Let’s look at a detailed example.
var arr = ['a', 'b', 'c', 'd', 'e']; function add(x, y) { return x + y; } arr.reduce(add)
Next, let’s explore how the above code is executed.
In this code, reducer is add.
First of all, because we are executing add for the first time, the first element 'a' in the array will be used as the first parameter of add, and then the loop will start from the second element 'a' of the array b'start. This time, 'b' is the second argument to add.
After the first calculation, we get the result 'ab'. This result will be cached and used as param1 in the next addition calculation. At the same time, the third parameter 'c' in the array will be used as param2 of add.
Similarly, reduce will continue to iterate through the elements in the array, running 'abc' and 'd' as arguments to add.
Finally, after traversing the last element in the array, return the calculation result.
Now we have the result: 'abcde'.
So, we can see that reduce is also a way to traverse an array! It takes the value of each element in the array in turn and executes the reducer function.
But we can see that the above loop does not have that harmonious beauty. Because we take the first element of the array, which is 'a', as the initial param1, and then loop through the second element of the array to get param2.
In fact, we can specify the second parameter in reduce as the initial value of param1 of the reducer function, so that param2 will be obtained in a loop starting from the first element of the array.
The code is as follows:
var arr = ['a', 'b', 'c', 'd', 'e']; function add(x, y) { return x + y; } arr.reduce(add, 's')
This time, we use 's' as param1 when we first call the reducer, and then traverse sequentially starting from the first element array.
So we can rewrite our first code snippet using this syntax.
var arr = ['a', 'b', 'c', 'd', 'e']; function add(x, y) { return x + y; } arr.reduce(add, '')
Next, we will enter the actual programming chapter to experience the powerful power of reduce.
1. Accumulation and cumulative multiplication
If we want to get the sum of all elements in the array, what would you do?
Generally speaking, you might write like this:
function accumulation(arr) { let sum = 0; for (let i = 0; i < arr.length; i++) { sum = sum + arr[i]; } return sum; }
Of course, you may have other ways of writing, but as long as you use a for loop, the code will appear redundant.
Then let’s see what the accumulation function above does:
- Set the initial sum to zero
- Take out the first element in the array and find and
- Cache the result of the previous step in sum
- Take out other elements in the array in turn and perform the above operations
- Return the final result
We can see that when we describe the above steps in words, it is obvious that it conforms to the use of reduce. So we can use reduce to rewrite the above code:
function accumulation(arr) { function reducer(x, y) { return x + y } return arr.reduce(reducer, 0); }
If you are used to using arrow functions, the above code will look more concise:
function accumulation(arr) { return arr.reduce((x, y) => x + y, 0); }
One line of code!
当然,累积乘法和累加是完全一样的:
function multiplication(arr) { return arr.reduce((x, y) => x * y, 1); }
很多时候,我们在求和的时候需要加上一个权重,这样更能体现reduce的优雅。
const scores = [ { score: 90, subject: "HTML", weight: 0.2 }, { score: 95, subject: "CSS", weight: 0.3 }, { score: 85, subject: "JavaScript", weight: 0.5 } ]; const result = scores.reduce((x, y) => x + y.score * y.weight, 0); // 89
2、获取一个数组的最大值和最小值
如果要获取数组的最大值和最小值,可以这样写:
function max(arr){ let max = arr[0]; for (let ele of arr) { if(ele > max) { max = ele; } } return max; }
这和以前一样,如果我们使用reduce,我们可以在一行代码中完成。
let arr = [3.24, 2.78, 999]; arr.reduce((x, y) => Math.max(x, y)); arr.reduce((x, y) => Math.min(x, y));
3、计算数组中元素出现的频率
我们经常需要统计数组中每个元素出现的次数。reduce 方法可以帮助我们实现这一点。
function countFrequency(arr) { return arr.reduce(function(result, ele){ // Judge whether this element has been counted before if (result.get(ele) != undefined) { /** * If this element has been counted before, * increase the frequency of its occurrence by 1 */ result.set(ele, result.get(ele) + 1) } else { /** * If this element has not been counted before, * set the frequency of its occurrence to 1 */ result.set(ele, 1); } return result; }, new Map()); }
注意,我们使用map对象而不是对象来存储统计后的频率,因为数组中的元素可能是对象类型,而对象的key只能是字符串或符号类型。
这里有两个例子:
同样,如果要统计字符串中每个字符出现的频率,可以先将字符串转换为字符数组,然后按照上面的方法。
let str = 'helloworld'; str.split('').reduce((result, currentChar) => { result[currentChar] ? result[currentChar] ++ : result[currentChar] = 1; return result; }, {})
因为字符类型可以用作对象的键,所以我们这里不使用 Map。
4、多个数组的展平
function Flat(arr = []) { return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), []) }
通过reduce依次访问数组中的每个元素。如果我们发现元素还是一个数组,就递归调用 flat 方法。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of JavaScript array reduce() method usage example. 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

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

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

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
