# Reduce method of array

Posted Jun 15, 20202 min read

This article introduces the usage of array reduce, three common uses, and the introduction of self-implemented reduce.

### 1. Usage of reduce

Rookie tutorial:

The reduce() method receives a function as an accumulator, and each value in the array(from left to right) is reduced, and finally calculated as a value.
reduce() can be used as a higher-order function for compose functions.
Note:reduce() will not execute the callback function for an empty array.
Syntax:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

### 2. Usage example of reduce

It is difficult to understand the use of reduce just by the text description. Here are some common usage scenarios.

#### Sum of arrays

``````    const arr=[1,2,3,4,5,6]
const sum=arr.reduce(
(prev,item)=>prev+item,//The first parameter is the callback function used for calculation
0//The second parameter is the initial value of prev
)``````

In the above code, `item` is an array element of `every item`. In the first execution, `prev=0`; in the second execution, the value of `prev` is the return value of the previous execution , That is, `prev+item`, until the completion of `array traversal execution` and return the final result, which is equivalent to
`0+arr+arr...`
In the callback function for calculation, we can write the logical judgment we need, for example, to sum the elements greater than 4 in the array, and add a judgment statement:

``const sum=arr.reduce(``

(prev,item)=>item>4?prev+item:prev,
0
)

Array deduplication
Reduce can be used for array deduplication:

``````        const arr = [1, 2, 3, 4, 5, 1, 1, 5, {}, {}, null, null, NaN, NaN]
const arr2 = arr.reduce((init, item) => {
init.includes(item)? null:init.push(item)
return init;
}, [])
console.log(arr, arr2);``````

Taking an empty array init as the initial value, it is determined whether the empty array init contains the element being traversed during traversal. If it exists, no operation is performed. If it does not exist, the element is inserted into the init array, and finally the init array is returned.
The includes method cannot deduplicate empty objects.
Used in the framework
For example, in vue, you want to parse {{person.friend.name}} in the page

``````//Analog data
const data = {
person:{
friend:{
name:'forceddd'
}
}
}
//Simulated string
const str ='person.friend.name'
const res = str.split('.').reduce(
(data, key) => data[key],
data
)
console.log(res);//'forceddd'``````

Vue first gets the string `person.friend.name`, converts it into an array through split, and then uses the reduce method to easily get the value in data, which is equivalent to `data[person][friend][name]`.

### 3. Implementation of Reduce

``````    Array.prototype.myReduce = function(cb, init = 0) {
if(typeof cb !=='function') {
throw new Error('The first parameter should be a function')
}
if(!this.length) {
throw new Error('Array cannot be an empty array')
}
for(let i = 0; i <this.length; i++) {
//Traverse the array and use the return value of the callback function as the next init
init = cb(init, this[i], i, this);
}