This article looks at one of the more difficult array methods to understand: reduce

First, we bring out the reduce method model:

array.reduce((pre,cur,index,arr)=>{},init)

Next, focus on understanding the characteristics of each parameter in the following model:

Arr: indicates the original array to be operated. 2. Pre: indicates the return value of the last call to the function. 3. Cur: refers to the current element operated on when the function was called. When you enter the function for the first time, the index for cur is 0 if there is init, and 1 if there is no init instead of init with pre. 4. Index: indicates the index value of the current operation element cur. 5. Init: The initial value when the reduce function is first entered, and how it is used is critical.Copy the code

Typically, the two parameters you end up using the Reduce method are Pre and CUR

So let’s start with the simplest example of how to use the Reduce method. Array summation as follows:

Const arr = [1,2,3,4] const res = arr.reduce((pre,cur)=>{return pre+cur},) The value of pre is 1 of index 0, and the index of cur is 1. Console. log(res) // Prints 10Copy the code

So what if init is set to 2

Const arr = [1,2,3,4] const res = arr.reduce((pre,cur)=>{return pre+cur},2) Console. log(res) // Outputs 12Copy the code

Let’s use an example of counting people’s names to further understand the Reduce approach

Let person = [" Jack ","Daivd"," Nick "," Mike "," Nick "] let data = person.reduce((pre,cur)=>{ If (cur in pre){pre[cur]++} else{pre[cur] = 1} return pre }, {})// Set the initial value to {} to facilitate the count of people's names. Console. log(data) // outputs {jack: 1, Daivd: 1, Nick: 2Copy the code