mapThe function takes a function as an argument, and the function as an argument takes three values: each element in the array, the element’s 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. This is the core of the implementation

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.

Reduce implementation map

Array.prototype._map = function (callback) {
  if(typeof callback === 'function') {
    return this.reduce((prev,item,index,arr) = > {
      prev.push(callback(item, index, arr))
      return prev
    }, [])
  } else {
    console.log(new Error('callback is not function'))}}let val = [1.5.6]._map(item= > item+ 1)
console.log(val);  / / [2, 6, 7)
Copy the code

The implementation of filter is the same as the implementation of map, except that the former is to put all the results into an array, and filter needs to make a judgment: 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

Reduce implementation filter

  Array.prototype._filter = function (callback) {
    if(typeof callback === 'function') {
      return this.reduce((prev,item,index,arr) = > {
        callback(item, index, arr) ? prev.push(item) : null
        return prev
      }, [])
    } else {
      console.log(new Error('callback is not function'))}}let val = [1.5.6]._filter(item= > item > 2)
  console.log(val);  / / [5, 6]
Copy the code

Find the maximum/minimum value

  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

Array to heavy

let arr = [1.2.3.1.1.2.3.3.4.3.4.5]

let result = arr.reduce((prev, item, index, arr) = > {
!prev.includes(item) && prev.push(item);
return prev
}, [])
console.log(result);  //[1, 2, 3, 4, 5]

Copy the code

Array flattening

let arr = [1.2.'3js'[4.5[6], [7.8[9.10.11].null.'abc'] and {age: 58},13.14]], '[]'.null];
function f(arr) {
    if(Array.isArray(arr)) {
      return arr.reduce((prev, item) = > {
        return Array.isArray(item) ? prev.concat(f(item)) : prev.concat(item)
      }, [])
    } else {
      throw new Error("arr + ' is not array'")}}Copy the code

Results: