Reduce is a new API introduced in ES5.

If you do not know how to use reduce, please read the MDN documentation about reduce first. (I have to say, the MDN documentation is too powerful to list many useful methods.)

This article describes some of the functionality you can do with the reduce function by iterating through every element of an array and using the results of the last iteration.

1. Fatigue and/or accumulation

let arr = [1.2.3.4.5]

console.log(arr.reduce((prev, cur) = > prev + cur)) / / 15

// Can implement alternative factorials
console.log(arr.reduce((prev, cur) = > prev * cur)) / / 120
Copy the code

2. Find the maximum/minimum

let arr = [1.2.3.4.5]

console.log(arr.reduce((prev, cur) = > Math.max(prev, cur))); / / 5

console.log(arr.reduce((prev, cur) = > Math.min(prev, cur))); / / 1
Copy the code

3. Array deduplication

When reduce receives two arguments, reduce(fn, init), init is passed in as fn’s first argument prev.

Here, an empty array [] is used as a new array, and nothing is done if an element already exists in the container. Conversely, if the container does not already contain an element, it is pushed into the container.

let arr = [1.2.3.1.1.2.3.3.4.3.4.5]
let res = arr.reduce((prev, cur) = >{
  !prev.includes(cur) && prev.push(cur)
  return prev
}, [])

console.log(res) // [1, 2, 3, 4, 5]
Copy the code

4. Implement the Map function

The map function takes a function as a parameter, and the function as a parameter takes three parameter values: each element in the array, the element index, and the array itself. These three arguments correspond to arguments 2, 3, and 4 of the first function argument received by the Reduce function.

The idea is to take each iterated element as an argument to the function passed in, and put the result of the function execution into a new array.

let arr = [1.2.3]
Array.prototype._map = function(cb) {
  if(typeof cb === 'function') {
    // this: The current array object that calls the _map method
    let arr = this;
    return arr.reduce((prev, item, index, array) = > {
      prev.push(cb(item, index, array))
      return prev
    }, [])
  } else {
    throw new Error(cb + ' is not function')}}let res = arr._map(n= > n*2)
console.log(res) // [2, 4, 6]
Copy the code

Implement the filter function

The implementation of filter is the same as the implementation of map, except that the latter is to put all the results into an array, and filter needs to make a decision: If the filter function passes an argument (the argument is a function) that returns a value, that is, the current element is checked before it is put into the array. If there is no return value, it is ignored.

let arr = [1.2.3.4.5];

Array.prototype._filter = function(cb) {
  if(typeof cb === 'function') {
    let arr = this;
    return arr.reduce((prev, item, index, array) = > {
        cb(item, index, array) ? prev.push(item) : null
        return prev
    }, [])
  } else {
    throw new Error(cb + ' is not function')}}let res = arr._filter(n= > n>2)
console.log(res) // [3, 4, 5]
Copy the code

6. Implement compose

Compose is the core idea of functional programming, which consists of composing several functions into a single function for execution. The result of each function execution can be used as an argument to the next function. This is also the idea behind using Reduce to implement Compose.

Suppose we have two functions that capitalize a string and append an exclamation point to the end of the string:

function toUpperCase(str) {
  return str.toUpperCase();
}

function add(str) {
  return str += '! '
}
Copy the code

In general, this is used:

var str = 'hello world'
var res = toUpperCase(str)
res = add(res)
console.log(res); // HELLO WORLD!
Copy the code

Using compose, the effect looks like this: fn is the same as toUpperCase and add in turn:

var fn = compose(add, toUpperCase)
console.log(fn(str));// HELLO WORLD!
Copy the code

Now implement compose:

function compose() {
  let args = [].slice.call(arguments)

  return function (x) {
   // Because compose() receives function arguments that are executed sequentially from the right,
   // Therefore, use reduceRight, which is the same as reduce, except that you go through the number groups from right to left.
    return args.reduceRight((prev, cur) = > {
      return cur(prev)
    }, x)
  }
}
Copy the code

7. Array flattening

Array flattening, for a multidimensional array, flattens and expands it to become a one-dimensional array.

let arr = [1.2.'3js'[4.5[6], [7.8[9.10.11].null.'abc'] and {age: 12},13.14]], '[]'];

function flatten(arr) {
  if(Array.isArray(arr)) {
    return arr.reduce((prev, cur) = > {
       // If the current item being iterated over is an array, iterate over and flatten out
      return Array.isArray(cur) ? prev.concat(flatten(cur)) : prev.concat(cur)
    }, [])
  } else {
    throw new Error(arr + ' is not array')}}console.log(flatten(arr));
Copy the code

The end of the

Of course, in addition to the above, reduce has more magical applications, waiting for you to discover and use.