First of all, referred to the summary of this big guy, knock again, the harvest is very big. Write it down. jump

Background:

When I came into contact with vue source code, I found a lot of places to use Reduce. At that time was also looking at others to share, simple belt, found very easy to use. After a brief study, it’s rarely used. Lead to not deep understanding. Today, I came across the use scenario and spent some time to study it. It can be said that I understand it well.

grammar

arr.reduce(function(prev,cur,index,arr){... }, init);Copy the code

Where, ARR represents the original array; Prev represents the return value from the last call to the callback, or the initial value init; Cur represents the array element currently being processed; Index represents the index of the array element being processed, 0 if init is provided, 1 otherwise; Init represents the initial value. 【 This initial value is used in many techniques, so pay attention to it. 】

In practice, only two parameters are commonly used: prev and CUR. Analyze with examples.

The instance

The following examples show that there are many other ways to do this than using Reduce. But using Reduce has its own tricks and conveniences.

1. Find the sum of arrays

A:

let arr = [3.4.5.6.9.2.4.6];
let sum = arr.reduce((pre,cur,index,arr) = >{
    // console.log('index:',index);
    // console.log('arr:',arr);
    return pre + cur;
})
console.log(sum);
Copy the code

Method 2:

let sum = arr.reduce((pre,cur,index,arr) = >{
    // console.log('index:',index);
    // console.log('arr:',arr);
    return pre + cur;
},0)
console.log(sum);
Copy the code

Note that the initial value of pre is 0, and the initial value of cur is 3. If you don’t pass the initial value, as in method one, then the value of pre is 3, and the value of cur is 4; That adds up to 7, which is the value of the next round of pre, which is 5, and so on.

2. Find the maximum value of the array

A:

let arr = [1.4.5.6.9.2.4.6];
let max  =  arr.reduce((pre,cur) = >{
    return Math.max(pre,cur)
})
console.log(max);
Copy the code

Method 2:

let max2 = arr.reduce((pre,cur) = >{
    return pre > cur ? pre:cur;
})
console.log('max2:',max2);
Copy the code

3. Deduplicate the array

let newArr = arr.reduce((pre,cur) = >{
    pre.indexOf(cur) === -1 && pre.push(cur)
    return pre
},[])
console.log(newArr);
Copy the code

Advanced usage

1. Count the number of subtitle occurrences in a string

const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';
const res = str.split(' ').reduce((pre,cur) = >{
    pre[cur] ? pre[cur]++ : pre[cur] = 1;
    return pre
},{})
console.log('Summary times:',res);
Copy the code

2. Array to array

let arr1 = [2.3.4.5.6.7];
let newArr1 = arr1.reduce((pre,cur) = >{
    pre.push(cur*cur)
    returnpre; }, [])console.log('Array to array:',newArr1);
Copy the code

3. Array to object

let streams = [{ name: '博士'.id: 1}, {name:'master'.id:2}, {name: 'bachelor'.id:3}];
let obj1 = streams.reduce((pre,cur) = >{
    pre[cur.id] = cur;
    returnpre; }, {})console.log(Array to object:,obj1);
Copy the code

Advanced usage

1. Multi-dimensional superposition execution operation

Example: the grade proportion of each subject is not the same, find the result

const result = [
    { subject: 'math'.score: 99},
    { subject: 'chinese'.score:95},
    { subject: 'english'.score:80},];const dis = {
    math: 0.5.chinese: 0.2.english: 0.4
};
let res2 = result.reduce((pre,cur) = >{
    return dis[cur.subject] * cur.score + pre
},0)
console.log('Multidimensional stack:',res2);
Copy the code

Increase difficulty: commodities correspond to different exchange rates in different countries, and seek prices

const prices = [{price: 23}, {price: 45}, {price:56}];
const rates = { us: '6.5'.eu:'7.5'};
const initialState = { usTotal: 0.euTotal: 0};
const res3 = prices.reduce((pre1,cur1) = > Object.keys(rates).reduce((pre2,cur2) = >{
    pre1[`${cur2}Total`] += cur1.price * rates[cur2];
    return pre1;
},{}),initialState)
console.log(res3);
Copy the code

2. Flatten a two-dimensional array

const arr4 = [ [1.2.3], [4.5.6], [7.8.9]].const res4 = arr4.reduce((pre,cur) = >{
    return  pre.concat(cur)
},[])
console.log('Flat a two-dimensional array',res4);
Copy the code

Multidimensional array flattening

3, object array deduplication

const hash = {};
chatLists = chatLists.reduce((obj,next) = >{
    const hashId = `${next.topic}_${next.stream_id}`;
    if(! hash[hashId]){ hash[`${next.topic}_${next.stream_id}`] =true;
        obj.push(next)
    }
    returnobj; }, [])Copy the code

Compose function

Redux compose source code implementation

function compose(. funs){
    if(funs.length === 0) {return arg= > arg
    }
    if(funs.length === 1) {return funs[0]}return funs.reduce((a,b) = >(. arg) = >a(b(... arg))) }Copy the code