Magical place on reduce the array of

In the front-end development process or the interview process, you were asked an array of common operations, you may immediately answer immediately forcycle, forEach, for..of, map, some...... reduceand other methods. I believe the front-end development of small partners, 10 people have eight pairs reducejust to stay in the data plus tired, here are some of my reduceoffice Magical function.

First, the review under the reduceparameters of the problem function

  • 1, reducefunction

    Array.prototype.reduce(function(previousVal, currentVal, index, _this) {
      // 函数体
    }, initVal);
    复制代码
  • 2, be understood that the above function

    • 1. The reducefunction is also an array iterative process
    • 2. The first cycle time, previousVal==initValthe
    • 3. From the second time, previousVal==reducerthe function returns the value of the
    • 4, indexshowing the array of the current sequence
    • 5, _thisrepresenting the current array

Second, to manually implement a reducefunction

  • 1, an array of its own expansion method

    Array.prototype.myReduce = function(fn, initVal) {
      if (Object.prototype.toString.call(this) != '[object Array]') {
        throw new Error('当前是数组的方法,不能使用到别的上面');
      }
      let total;
      if (initVal != undefined) {
        total = initVal;
      } else {
        total = this[0];
      }
      if (initVal === undefined) {
        for (let i = 1; i < this.length; i++) {
          total = fn(total, this[i], i, this);
        }
      } else {
        for (let [index, val] of this.entries()) {
          total = fn(total, val, index, this);
        }
      }
      return total;
    };
    复制代码

A data accumulation

  • 1, the original data

    let ary1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    复制代码
  • 2, data overlay

    const result = ary1.reduce((pre, cur) => pre + cur);
    console.log(result);
    复制代码

Second, convert the array object

  • 1, implementation code

    const userList = [
      {
        id: 1,
        username: 'john',
        sex: 1,
        email: '[email protected]'
      },
      {
        id: 2,
        username: 'jerry',
        sex: 1,
        email: '[email protected]'
      },
      {
        id: 3,
        username: 'nancy',
        sex: 0,
        email: ''
      }
    ];
    
    let result = userList.reduce((pre, current) => {
      return {...pre, [current.id]: current};
    }, {});
    
    console.log(result);
    复制代码

Third, to convert large array into smaller arrays

  • 1, implementation code

    const fileLines = [
      'Inspector Algar,Inspector Bardle,Mr. Barker,Inspector Barton',
      'Inspector Baynes,Inspector Bradstreet,Inspector Sam Brown',
      'Monsieur Dubugue,Birdy Edwards,Inspector Forbes,Inspector Forrester',
      'Inspector Gregory,Inspector Tobias Gregson,Inspector Hill',
      'Inspector Stanley Hopkins,Inspector Athelney Jones'
    ];
    
    let result = fileLines.reduce((pre, current) => {
      return pre.concat(current.split(/,/g));
    }, []);
    
    console.log(result);
    复制代码

Fourth, expand the array

  • 1, implementation code

    const arr = ["今天天气不错", "", "早上好"];
    
    const arr2 = arr.reduce((pre, cur) => {
      return pre.concat(cur.split(''));
    }, []);
    console.log(arr2);
    复制代码

Five, the maximum and minimum demand array

  • 1, implementation code

    const readings = [0.3, 1.2, 3.4, 0.2, 3.2, 5.5, 0.4];
    
    let minValue = readings.reduce((x,y) => Math.min(x,y));
    console.log(minValue);
    let maxValue = readings.reduce((x,y) => Math.max(x,y));
    console.log(maxValue);
    复制代码

Sixth, the use reducewriting tools a method for extracting data objects

  • 1, a rear end of the object returned

    let obj1 = {
      "result": {
        "report": {
          "contactInfo": {
            "callsNumber": 0,
            "contactsNumber": 0,
            "emergencyContactHasOverdue": "No",
            "sameLiainson": {
              "isSame": "Yes",
              "accounts": "aa"
            }
          }
        }
      }
    };
    复制代码
  • 2, using the reducetools of the method

    const objectGetVal = (obj, expr) => {
      if (!Object.is(Object.prototype.toString.call(obj), '[object Object]')) {
        throw new Error(`${obj}不是对象`);
      }
      if (!Object.is(Object.prototype.toString.call(expr), '[object String]')) {
        throw new Error(`${expr}必须是字符串`);
      }
      return expr.split('.').reduce((prev, next) => {
        if (prev) {
          return prev[next]
        } else {
          return undefined;
        }
      }, obj)
    };
    console.log(objectGetVal(obj1, 'result.report.contactInfo.emergencyContactHasOverdue'));
    console.log(objectGetVal(obj1, 'result.report.emergencyContactHasOverdue'));
    // 输出结果
    // No
    // undefined
    复制代码

Seven, the use of reducegenerated tree menu reference

Reproduced in: https: //juejin.im/post/5d073414f265da1b6029037f

Guess you like

Origin blog.csdn.net/weixin_34336292/article/details/93162511