This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging


Note: Part of the content and pictures from the network, if there is any infringement, please contact me (home page has the public number: Small siege city Lion science front end)

Author: small front siege city lion, home: small front siege city lion’s home page, source: Nuggets

GitHub: P-J27, CSDN: PJ wants to be a front end siege lion

The copyright belongs to the author. Commercial reprint please contact the author to obtain authorization, non-commercial reprint please indicate the source.


preface

In this article, we will read the contents of JS array in detail. This article is about “Array traversal (5)”, and the previous article is about portal


reduce()

Action: The reduce() method receives a function as an accumulator, and each value in the array (from left to right) begins to shrink, eventually calculating to a single value. The return value is the result of the cumulative processing of the callback function.

Grammar:

arr.reduce(function (previousValue, currentValue, currentIndex, arr) {... }, initialValue);Copy the code
  • PreviousValue: Mandatory, the value returned when the callback function was last called
  • CurrentValue: Mandatory, the array element currently being processed
  • CurrentIndex: Optional, the index of the array element being processed
  • Arr: An optional array of reduce() methods to call
  • InitialValue: This parameter is optionalThe initial value(The value passed to previousValue when the callback is first called)

In the previous array method, the anonymous callback function passed three parameters: item, index, and arr. But in the reduce() method, an extra parameter previousValue is passed, which means the return value from the last call to the callback. What if previousValue has no value when the callback is executed the first time? You can pass it the initialValue parameter as the initialValue.

Note: Many people are confused when they first come into contact with reduce(), I am the same, but write a few examples, something to read several times, naturally master. Reduce is also a commonly used high-order function to improve efficiency in development. If we can master the use of reduce(), we will be able to replace many other array methods and gradually step up the ladder

To understand reduce(), let’s take a look at the following simple code and test the waters: HHHH…. :

let arr1 = [1, 2, 3, 4, 5, 6]; Let res = arr1.reduce((prev, item) => {console.log(' the last number is ',prev); Console. log(' current number is ',item); console.log('------'); return 88; }, 0); Console. log('reduce 'returns: ',res) /* The previous number is 0 the current number is 1 ------ the previous number is 88 the current number is 2 ------ The previous number is 88 the current number is 3 ------ the previous number is 88 the current number is 4 ------ the previous number is 88 the current number is 5 ------ The preceding number is 88. The current number is 6. ------ The return value of reduce is 88 */Copy the code

In the above code, since return is a fixed value, prev prints a fixed value (only the initial value is 0, and the rest of the traversal prints 88). We can see that the return value of reduce is the result of the last callback, and it is not empty or an array.

Now for an upgrade, in real development, prev values tend to change dynamically, which is the subtlety of Reduce (). So let’s look at a couple of examples.


application

sum

Calculates the sum of all elements in an array. Code implementation:

const arr = [2.0.1.9.6];
// Array summation
const total = arr.reduce((prev, item) = > {
 ย  ย return prev + item;
});
console.log('total:' + total); // Print the result: 18
Copy the code
Count the number of occurrences of an element
// Define method: unify the number of occurrences of the value element in array arr
function repeatCount(arr, value) {
 ย  ย if(! arr || arr.length ==0) return 0;
โ€‹
 ย  ย return arr.reduce((totalCount, item) = > {
 ย  ย  ย  ย totalCount += item == value ? 1 : 0;
 ย  ย  ย  ย return totalCount;
 ย   }, 0);
}
โ€‹
let arr1 = [1.2.6.5.6.1.6];
โ€‹
console.log(repeatCount(arr1, 6)); // Print the result: 3
Copy the code
Find the maximum value of the element
const arr = [2.0.1.9.6];
// Maximize the array
const maxValue = arr.reduce((prev, item) = > {
 ย  ย return prev > item ? prev : item;
});
console.log(maxValue); // Print the result: 9
โ€‹
Copy the code

Summary: is it found that reduce is very diao, very NP. In fact, he has many, many more applications, which is really a great tool in development.

Write in the last

Before you know it, the entire array series is finished. At the same time, I am also reviewing learning. A lot of things are easy to forget after a long time. Over and over again, in addition to consolidating, I have a deeper understanding of the knowledge. Preview the next installment: Function series


Thank you for reading, I hope it can help you, if there are mistakes or infringement of the article, you can leave a message in the comment area or add the public account in my home page to contact me.

Writing is not easy, if you feel good, you can “like” + “comment” thanks for supporting โค