“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

Record knowledge and make progress every day

1, grammar,

array.reduce(function(prev, cur, index, arr), initialValue) // Shorthand is easy to explainarr.reduce(callback,[initialValue])
Copy the code

Parameter Meaning:

Callback (function that executes each value in the array, with four arguments)1PreviousValue (the value returned by the callback on the last call, or the initialValue provided)2CurrentValue (the element currently being processed in the array)3Index (the index of the current element in the array)4InitialValue (as the first argument in the first callback call). Similar to setting the initial valueCopy the code

2. The instance parses the initialValue parameter

Let’s look at the first example:

var arr = [1.2.3.4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr, sum);
// Print the result:
/ / 1 2 1
3 2 / / 3
/ / 6 4 3
//[1, 2, 3, 4] 10
Copy the code

As you can see, the above example index starts at 1, and the first prev is the first value in the array. The array length is 4, but the reduce function loops three times.

Look at the second example:

var  arr = [1.2.3.4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
},0) // Note that the initial value is set
console.log(arr, sum);
// Print the result:
/ / 1 0 0
/ / 1 2 1
3 2 / / 3
/ / 6 4 3
//[1, 2, 3, 4] 10
Copy the code

In this example, the index starts at 0, the first prev is 0, which is the initial value we set, the array length is 4, and the reduce function loops 4 times.

Conclusion: If initialValue is not provided, Reduce executes the callback method starting at index 1, skipping the first index. If initialValue is provided, start at index 0. Note: If this array is empty, what happens with Reduce?

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

However, if we set the initial value, there will be no error, as follows:

var  arr = [];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    returnprev + cur; },0)
console.log(arr, sum); / / [] 0
Copy the code

So in general it’s safer for us to provide the initial value

3. Simple usage of reduce

And of course the easiest thing to do is to take the sum of arrays, the product that we always use.

var  arr = [1.2.3.4];
var sum = arr.reduce((x,y) = >x+y)
var mul = arr.reduce((x,y) = >x*y)
console.log( sum ); // Sum, 10
console.log( mul ); // Take the product, 24
Copy the code

4. Advanced usage of reduce

(1) Count the number of occurrences of each element in the array

let names = ['Alice'.'Bob'.'Tiff'.'Bruce'.'Alice'];
let nameNum = names.reduce((pre,cur) = >{
  if(cur in pre){
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
Copy the code

(2) Deduplicate arrays

let arr = [1.2.3.4.4.1]
let newArr = arr.reduce((pre,cur) = >{
    if(! pre.includes(cur)){return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);// [1, 2, 3, 4]
Copy the code

(3) Convert a two-dimensional array into a one-dimensional array

let arr = [[0.1], [2.3], [4.5]]
let newArr = arr.reduce((pre,cur) = >{
    return pre.concat(cur)
},[])
console.log(newArr); // [0, 1, 2, 3, 4, 5]
Copy the code

(3) Convert multidimensional arrays into one-dimensional ones

let arr = [[0.1], [2.3], [4[5.6.7]]]
const newArr = function(arr){
   return arr.reduce((pre,cur) = >pre.concat(Array.isArray(cur)? newArr(cur):cur),[]) }console.log(newArr(arr)); //[0, 1, 2, 3, 4, 5, 6, 7]
Copy the code

(4) The sum of properties in the object

var result = [
    {
        subject: 'math'.score: 10
    },
    {
        subject: 'chinese'.score: 20
    },
    {
        subject: 'english'.score: 30}];var sum = result.reduce(function(prev, cur) {
    return cur.score + prev;
}, 0);
console.log(sum) / / 60
Copy the code