reduce the good stuff

reduce () method can handle things, for loop, or forEach method sometimes can get, then why use reduce ()? This question, before I thought, really can not find reason to say, the only way to find is: there are many roads to success, but there is always a way to be the most shortcut, it may also reduce () to force the grid more high...

1, grammar

arr.reduce(callback,[initialValue])

 

reduce each of the array element to the callback order, including elements in the array are not deleted or never assigned, it accepts four parameters: the initial value (or the last of the return value of the callback function), the element current value, the current index, reduce the array of call.

callback (function execution for each value in the array, comprising four parameters)

    . 1 , previousValue (a call to the value of the callback returned, or starting values (the initialValue))
     2 , currentValue (current element being processed in the array)
     . 3 , index (current index of the element in the array)
     . 4 , Array ( call to reduce the array)

initialValue (first call as the first parameter of the callback.)

 

2, examples of analytic parameter initialValue

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 Results:
1 2 1
3 3 2
. 6 4 3
[1, 2, 3, 4] 10

Here it can be seen from the above example 1 starting index, the first value of prev is the first value of the array. Length of the array is 4, three cycles but reduce function.

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 an initial value set 
console.log (arr, sum);

 

Print Results:
0 1 0
1 2 1
3 3 2
. 6 4 3
[1, 2, 3, 4] 10

This example is the index starting from 0, the first value is the initial value of 0 prev we set the length of the array is 4, the reduce function of four cycles.

in conclusion:如果没有提供initialValue,reduce 会从索引1的地方开始执行 callback 方法,跳过第一个索引。如果提供initialValue,从索引0开始。

Note: If this array is empty, reduce the use of what is the situation?

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"

 

But if we set the initial value of the error will not, as follows:

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

 

So in general we provide an initial value is typically safer

3, reduce the use of simple

Of course, the simplest is our usual array sum, the product.

var  arr = [1, 2, 3, 4];
var sum = arr.reduce((x,y)=>x+y)
var mul = arr.reduce((x,y)=>x*y)
the console.log (SUM); // sum, 10 
the console.log (MUL); // find product, 24

 

4, reduce the Advanced Usage

Number (1) is calculated for each array element appears

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}

 

(2) an array of deduplication

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]

 

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

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]

 

(3) The multi-dimensional array into a one-dimensional

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]

 

(4), the properties of the object in sum

was resulted = [
    {
        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

 



Author: _littleTank_
link: https: //www.jianshu.com/p/e375ba1cfc47
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/zqxi/p/12093072.html