preface

My girlfriend asked me if I could tell her about Reduce. Considering that I didn’t have a deep understanding of Reduce before, I would like to take advantage of explaining it to her to solidify it.

grammar

arr.reduce(callback, [initialValue])
Copy the code

Reduce executes the callback function for each element in the array, excluding elements that were deleted or never assigned. The callback function takes four arguments:

  • An accumulator cumulative device
  • The current value currentValue
  • CurrentIndex indicates the currentIndex
  • Array an array

initialValue

InitialValue is an optional value. It seems not very important, but it has a significant impact on Accumulator and currentValue.

When initialValue does not exist

let arr = [1.2.3.4];
let sum = arr.reduce((acc, cur, index) = >{
 console.log(acc, cur, index);
 return acc + cur;
});
console.log(sum) Copy the code

The output is:

1 2 1
3 3 2
6 April 310
Copy the code

If initialValue is not present, the accumulator is the first element in the array and currentValue is the second element in the array. The accumulator is the return value of the previous loop. CurrentValue is the next element, and the array has four elements, but it only loops three times.

When initialValue exists

let arr = [1.2.3.4];
let sum = arr.reduce((acc, cur, index) = >{
 console.log(acc, cur, index);
 return acc + cur;
}, 0);
console.log(sum); Copy the code

The output is:

1 0 01 2 1
3 3 2
6 April 310
Copy the code

In the example above, when initialValue exists, the accumulator is the value of initialValue in the first loop, and currentValue is the first value in the array. The accumulator is the return value of the previous loop. CurrentValue is the next element, and there are four elements in the array, so we have executed four loops.

When the array is empty

let arr = [];
let sum = arr.reduce((acc, cur, index) = >{
 return acc + cur;
})
"TypeError: Reduce of empty array with no initial value"
Copy the code
let arr = [];
let sum = arr.reduce((acc, cur, index) = >{
 return acc + cur;
}, 0)
console.log(sum); / / 0
Copy the code

When the array is empty and initialValue is not written, an error is reported, so try to fill in initialValue just in case.

The application of the reduce

There are many kinds of loops, so why apply Reduce? Is it to improve the force!! In fact, this may not be ruled out 😂 here are some reduce operations:

1, the sum

let arr = [1.2.3.4.5.6];
let sum = arr.reduce((acc, cur) = >{
 return acc + cur;
}, 0)
console.log(sum); 
Copy the code

2. A two-dimensional array is reduced to a one-dimensional array

let arr = [[1.2], [3.4], [5.6]].let flattened = arr.reduce((acc, cur) = >{
 return acc.concat(cur);
}, [])
Copy the code

3. Count the number of occurrences of each element in the array

Say this question at the time of the interview encountered, is an English article, the number of letters, in fact, similar to this, at that time to write very complex, now think if at the beginning of the choice of this method will be much better.

let names = ['James', 'Bob', 'Alice', 'Bob', 'John'];
let countedNames = names.reduce((acc, cur) = >{
 if (cur in acc) {
  acc[cur]++;
 } else {
 acc[cur] = 1;  }  return acc; }, {}) Copy the code

4. Classify objects by attributes

let people = [
 {name: 'Alice', age: 21},
 {name: 'James', age: 20},
 {name: 'John', age: 20}
];
const groupBy = (objectArray, property) = >{  return objectArray.reduce((acc, cur) = >{  let key = cur[property];  if(! acc[key]) { acc[key] = [];  }  acc[key].push(cur);  return acc;  }, {}) }; letGruopedPeople = groupBy (people, "age");Copy the code

5. Deduplicate arrays

let arr = [1.1.1.2.2.2.3.3.3.4.5];
let result = arr.reduce((acc, cur) = >{
 if(! acc.includes(cur)) {  acc.push(cur);
 } 
 return acc; }, []) Copy the code

Compose function in Redux

The official code is as follows:

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

The return value for compose is also a function, and the argument passed to this function will be called from the inside out as the argument to the last parameter of compose. Reduce execution process:

funcs = [f1, f2, f3];
loop1: a = f1, b = f2, ret1 = (. args) = >f1(f2(... args))loop2: a = ret1, b = f3, ret2 = (. args) = >ret1(f3(... Args)), i.e. ret2 =(. args) = >f1(f2(f3(... args)))Copy the code

After the language

I think it’s ok, please give me a thumbs up when I leave, and we can study and discuss together!

You can also follow my blog and hope to give me a Start on Github, you will find a problem, almost all my user names are related to tomatoes, because I really like tomatoes ❤️!!

The guy who wants to follow the car without getting lost also hopes to follow the public account or scan the qr code below 👇👇👇. After attention, I pull you into the front end of the advanced group, we communicate together, learn together, also can get free information!!I am a primary school student in the field of programming, your encouragement is the motivation for me to keep moving forward, 😄 hope to refueling together.

This article was typeset using MDNICE