preface

The last article mainly introduced the basic grammar of Reduce and classic introduction examples, after familiar with, this article is mainly to share with friends reduce in our actual development what are the magic?

Address: Solid Foundation —– Reduce Advanced (I)

The body of the

Why is the output NaN

To review the question left by the previous section, why does the following code fragment execution output NaN?

    var maxCallback = ( acc, cur ) = > Math.max( acc.x, cur.x ); [{x: 2 }, { x: 22 }, { x: 42 } ].reduce( maxCallback ); 
Copy the code

When we call reduce, we do not pass in the default value, so the default value is resolved to an empty object. Then ** math.max (undefined,1)** will return NaN. Let’s talk about reduce in the comments section. Let’s talk about reduce in the comments.

Implement array deduplicating
    let arr = [{"all": 1}, {"all": 2}, {"all": 3}, {"all": 4}, {"all": 1}];
    let hash = {};
    arr = arr.reduce((item,next) = >{
        hash[next.all] ? "" : hash[next.all] = true && item.push(next);
        return item;
    },[]);
    console.log(arr);
Copy the code

When dealing with such an array of objects, using reduce seems more efficient than using filter or other traversal methods.

A multidimensional array becomes a one-dimensional array
    let arr = [[0.1.3], [2.3], [4].5.6.7[9.10.11]].const newArr = function(arr){
        return arr.reduce((pre,cur) = > pre.concat(Array.isArray(cur) ? newArr(cur) : cur),[])
     }

    console.log(newArr(arr));
Copy the code

The reduce function encapsulates the first parameter callback into an array, and each function in the array is added separately to complete the reduce operation. Everything is managed through a manager function and the initial parameters are passed.

Run the promises in sequence

In development scenarios where multiple asynchronous combinations are needed, we might use promis. Then to chain the call. When many functions are needed to chain the. Then callback is not elegant, we can try reduce. This is the MDN reference on a code snippet, feel very clear implementation of a chain call, friends can see several times, understand understanding, together to learn.

function runPromiseInsquence(arr, input) {
    return arr.reduce(
        (promiseChain, currentFunction) = > promiseChain.then(currentFunction),
        Promise.resolve(input)
    )
}
// function 1
function p1(a) {
    return new Promise((resolve, reject) = > {
        resolve(a * 5);
    });
}
// function 2
function p2(a) {
    return new Promise((resolve, reject) = > {
        resolve(a * 2); })}// function 3
function p3(a) {
    return new Promise((resolve, reject) = > {
        resolve(a * 3); })}// function 4
function p4(a) {
    return new Promise((resolve, reject) = > {
        resolve(a * 4); })}const promiseArr = [p1, p2, p3, p4];
runPromiseInsquence(promiseArr, 10).then();
Copy the code

Promise().then().then().then().then().then(); Not an array of promises. In addition, the second argument to the reduce() method, which is an initial value, in this case promise.resolve (), indicates that one action has completed and is ready to move on to the next.

How compatible is it?

Here I have checked the official data, the introduction is very detailed, we choose to use, must consider the compatibility, of course, if your project can introducebabelYou can use it safely.

conclusion

Reduce method, in a word, is still very powerful, interested in research partners can be more detailed to understand some, I believe there will be different harvest! The front long long distance, we are all on the road, hope to communicate with you, progress together. Keep updating ing…..