The reduce method of the js array

arr. reduce( function(prev, cur, index,arr){
}, init);
/ / or
arr. reduce( function(prev, cur , index,arr){});Copy the code

Arr represents the original array to be operated on (the original array to be operated on);

Prev represents the return value from the last call to the callback, or the initial value init;

Cur indicates the array element currently being processed;

Index indicates the index of the array element being processed. If init value is provided, the index is 0; otherwise, the index is 1.

Init indicates the initial value. There are only two commonly used parameters: prev and cur

role

1: Array sum, take the product. Take the product and take it

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

2: Calculates the number of occurrences of each element in the array

  let sb=['sb'.'sb'.'dsb'.'sb']
        let nameNum=sb.reduce((pre,cur) = >{
            if(cur in pre){
                pre[cur]++
            }else{
                pre[cur]=1
            }
            return pre
        },{})
        console.log(nameNum);
Copy the code

3: Deduplicates the array

  let sb = ['sb'.'sb'.'dsb'.'sb']
        let resNum = sb.reduce((pre, cur) = > {
            if(! pre.includes(cur)) {return pre.concat(cur)
            } else {
                return pre
            }

        }, [])
        console.log(resNum);
Copy the code

4: Convert a two-dimensional array into a one-dimensional array

5: Convert multidimensional arrays into one-dimensional arrays

Ps: four and five are almost the same

const arr = [1.2.2.3[9.8.7[5.2.1]]]
const flatten = arr= > {
    return arr.reduce(
        (pre, cur) = > {
            return pre.concat(Array.isArray(cur) ? flatten(cur) : cur); }}, [])const res4 = flatten(arr)

Copy the code