Grammar:

arr.reduce(function (prev, cur, index, arr) {... }, init)Copy the code
  • Arr stands for primitive array;
  • Prev represents the return value from the last call to the callback, or the initial value init;
  • Cur represents the array element currently being processed;
  • Index represents the index of the array element being processed, 0 if init is provided, 1 otherwise;
  • Init represents the initial value.

There are only two parameters commonly used :prev and CUR.

Common examples:

- Array summation, product - Count the number of occurrences of each element in the array - array de-duplication - Convert multidimensional array to one-dimensional array (array flattening)Copy the code

1- Array sum, take product

let arr = [1.2.3.5.8.10]
const result = arr.reduce((prev,cur) = >prev + cur)
console.log(result);    / / 29
Copy the code

2- Counts the number of occurrences of each element in the array

let person = ["Yang"."Dilieba"."Guan Xiaotong"."King Of Canada"."King Of Canada"."Yang"."Yang"]

let num = person.reduce((prev, cur) = > {
    if (prev.hasOwnProperty(cur)) {
        prev[cur]++
    } else {
        prev[cur] = 1
    }
    return prev
}, {})
console.log(num) //{' Yang Mi ': 3, 'Dilieba ': 1,' Guan Xiaotong ': 1, 'Canada king ': 2}
Copy the code

3- Array deduplication

let arr = [1, 1, 2, 3, 8, 3, 9, 10] let newarr = arr.reduce((prev, cur) => { if (! prev.includes(cur)) { return prev.concat(cur) } return prev }, []) console.log(newarr) //[ 1, 2, 3, 8, 9, 10 ]Copy the code

4.- Convert multidimensional arrays to one-dimensional arrays (array flattening)

let arr = [1, [2, [3, 4], 5,], 6, 7, 8, 9]
let fn = (arr) => {
 return arr.reduce((prev, cur) => {
      return  prev.concat( Array.isArray(cur) ? fn(cur) : cur )
    },[])
}
console.log( fn(arr))  //[1, 2, 3, 4, 5, 6, 7, 8, 9]

Copy the code