Today please let me introduce this method in detail, I hope it will be helpful to you. This is the basic usage of reduce: Reduce is a method on the array prototype object that helps us operate arrays. It takes another function as its argument, which can be called a reducer. reducer takes 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. Next, let's explore how the above code is executed. In this code, reducer is add. First, because we are executing add for the first time, the first element 'a' in the array will be treated as the first parameter of add, and then the loop will start from the second element 'b' of the array. 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. Likewise, reduce continues through the elements in the array, running 'abc' and 'd' as arguments to add. Finally, after traversing the last element in the array, the calculation result is returned. 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: This time, we first call the reducer with 's' as param1, and then iterate through the array starting from the first element. So we can rewrite our first code snippet using this syntax. Next, we will enter the actual programming chapter to experience the powerful power of reduce. What would you do if we wanted to get the sum of all elements in an array? Generally speaking, you might write something like this: Of course, you may have other ways of writing it, but as long as you use a for loop, the code will become redundant. Then let’s take a look at what the accumulation function above does: Set initial sum to zero Get the first element in the array and sum it Cache the result of the previous step in sum Take out other elements in the array in turn and perform the above operations return 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 rewrite the above code using reduce: If you're used to using arrow functions, the above code will look cleaner: One line of code and done! Of course, cumulative multiplication and accumulation are exactly the same: Many times, we need to add a weight when summing, which can better reflect the elegance of reduce. If you want to get the maximum and minimum values of an array, you can write: This is the same as before, if we use reduce we can do it in one line of code. We often need to count the number of occurrences of each element in an array. The reduce method helps us achieve this. Note that we use map objects instead of objects to store statistical frequencies, because the elements in the array may be of object type, and the keys of the objects can only be string or symbol types. Here are two examples: Similarly, if you want to count the frequency of each character in a string, you can first convert the string into a character array, and then follow the above method. Because character types can be used as keys for objects, we won't use a Map here. Each element in the array is accessed sequentially through reduce. If we find that the element is still an array, we call the flat method recursively. Preface
var arr = [1, 2, 3];
function reducer(parmar1, parmar2){
}
arr.reduce(reducer)
var arr = ['a', 'b', 'c', 'd', 'e'];
function add(x, y) {
return x + y;
}
arr.reduce(add)
var arr = ['a', 'b', 'c', 'd', 'e'];
function add(x, y) {
return x + y;
}
arr.reduce(add, 's')
var arr = ['a', 'b', 'c', 'd', 'e'];
function add(x, y) {
return x + y;
}
arr.reduce(add, '')
1. Accumulation and cumulative multiplication
function accumulation(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum;
}
function accumulation(arr) {
function reducer(x, y) {
return x + y
}
return arr.reduce(reducer, 0);
}
function accumulation(arr) {
return arr.reduce((x, y) => x + y, 0);
}
function multiplication(arr) {
return arr.reduce((x, y) => x * y, 1);
}
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. Get the maximum and minimum values of an array
function max(arr){
let max = arr[0];
for (let ele of arr) {
if(ele > max) {
max = ele;
}
}
return max;
}
let arr = [3.24, 2.78, 999];
arr.reduce((x, y) => Math.max(x, y));
arr.reduce((x, y) => Math.min(x, y));
3. Calculate the frequency of occurrence of elements in the array
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());
}
let str = 'helloworld';
str.split('').reduce((result, currentChar) => {
result[currentChar] ? result[currentChar] ++ : result[currentChar] = 1;
return result;
}, {})
4. Flattening of multiple arrays
function Flat(arr = []) {
return arr.reduce((t, v) => t.concat(Array.isArray(v) ? Flat(v) : v), [])
}