What is the reduce

The Mozilla Reduce () method executes a Reducer function (ascending) that you provide for each element in the array, summarizing the results into a single return value.

The reduce method is used to manipulate an array. When it is executed, it needs to provide a function parameter to process each element in the array. When it completes, the method returns a value. In other words, redux is a method that processes an array and returns a value when it’s done.

grammar

Reduce () receives a function as an accumulator (which operates on each element in the array), and each value in the array (from left to right) begins to shrink, eventually calculating to a single value. In addition to accepting a function, it also accepts an initialValue, initialValue, which can be a number, object, and so on.

const reducer = function(accumulator, currentValue, currentIndex, array){ /** some code... * * /}; const initialValue = {}; Array.reduce (Reducer, initialValue)Copy the code

Function parameters (Reducer)

const reducer = function(accumulator, currentValue, currentIndex, array){ /** some code... * * /};Copy the code
Function parameters (Reducer) four parameters are described:

1. Accumulator

The accumulator accumulates the return value of the callback; It is the cumulative value, or initialValue, that was returned when the callback was last called. In other words, the accumulator parameter obtained in the next execution of the Reducer function is the one returned by the previous execution of the reducer function. If this is the first execution, the accumulator parameter will be initialValue. If the initialValue does not exist, the first element in the array will be used.

2. CurrentValue indicates the currentValue

So this makes sense, that’s the element of the array that we’re dealing with

3. CurrentIndex indicates the currentIndex

Index of the array element being processed

4. The array array

The array of calls to reduce() is the array being manipulated

Dry rice (example)

1. Calculate the sum of the elements of the array

const numbers = [10, 20, 30]; // This method will be executed three times. // This method will be executed three times. // This method will be executed three times. Const getSum = (total, num)=> {const next = total + num; console.log(next) return next; } const sum = numbers.reduce(getSum, 0) console.log(sum); // Output: 60Copy the code

Isn’t that simple? It’s like you’re going through an array, and each time you’re going through a function that you’re writing, it’s going to return a value that you might get the next time you’re going through, and you can use that value to do whatever you want. The first time this value is acted as an initial value parameter.

2. Write a difficult logic to deal with something (baidu may not find or hard to find cases and explanations)

show code

What do these eight lines of code accomplish 🤔?

At first look at the use of the method is quite a lot, but take a closer look, harm, nothing more than Object. Keys,. Map,. Split, reduce these four methods just ~. First look at the demand, or comrades may not have time to finish the meal.


/ / has the following object literal data const foo1 = {' A ', 1, 'B.A: 2,' B.B: 4, 'CC. D.E: 3,' CC. D.F: 5} / / write A method will be formatted into: const foo1 = {" A ": 1, "B": { "A": 2, "B": 4 }, "CC": { "D": { "E": 3, "F": 5 } } }Copy the code

As you can quickly see, the idea is to unwrap strings linked with.symbols and make them into nested objects. Most of the choices we make when we do this kind of thing are recursion. In fact, using Reduce will result in better performance and more concise code.

Above code analysis:

Each key of the foo1 object is a string linked with a.sign, and the value is a number. That means that no matter how many layers of k there are on the left, the value on the right is only one, so you just need to split the left into an object, and then give the value on the right to the lowest level of the object.

  • The code analysis
  1. Object.keys(foo1)

    The first step is to retrieve all the keys of the target Object using object. keys.

   ["A", "A.B", "B.B", "CC.D.E", "CC.D.F"] 
Copy the code
  1. Object.keys(foo1).map(item=>item.split(‘.’))
    [
        ["A"], 
        ["A","B"],
        ["B","B"], 
        ["CC","D"."E"]", 
        ["CC","D","F"]
    ]
Copy the code
  1. When we need to operate on a two-dimensional array and return an object, we need to return the object we want, so we can go to the value of each property of foo1, which is the number on the right. It is also possible to get an array of keys for each property of foo1. We just need to nest the key into an object and assign the value to the lowest level of the object.

    This example certainly requires patience to understand 🤔

Object.keys(foo1).map(item=>item.split('.')).reduce((pre, cur)=>{//pre is an empty Object in the first execution, and the second execution is an array of objects in the last execution. Reduce (cPre, cCur, cIndex)=>{//cPre is an object, the first time it is executed is the same as pre. //cCur is a string, which is the name of the attribute of a specific level of the object. // If the provided accumulator (i.e., the object last handled) does not exist, then it is equal to an empty object {} if(! cPre[cCur]) cPre[cCur] = {}; // If the index of the current array element is equal to the index of the last element in the current array, If (cIndex === cur.length - 1) cPre[cCur] = foo1[cur.join('.')]; // Return an object. Note that if the object is empty, it should be set equal to {} on the next loop. Return cPre[cCur]}, pre) return cPre[cCur]}, pre)Copy the code

References: Mozilla-Reduce (here are some other examples worth looking at)