javascript實用數組方法梳理

  • 多維數組扁平化數組

    1. 利用reduce實現,以下:
    const flatArray = function (depth = 1) {
      let arr = Array.prototype.slice.call(this)
      if (depth === 0) return arr
        return arr.reduce((pre, cur) => {
          if (Array.isArray(cur)) {
            return [...pre, ...flatArray.call(cur, depth - 1)]
          } else {
            return [...pre, cur]
          }
        }, [])
    }
    
    const arr1 = [1, 2, [3, 4], [5, [6, 7]]]
    console.log(flatArray.call(arr1)) // [1, 2, 3, 4, 5, [6, 7]]
    console.log(flatArray.call(arr1, 2)) // [1, 2, 3, 4, 5, 6, 7]
    複製代碼
    1. 使用Array.prototype.flat()方法
    const arr1 = [1, 2, [3, 4], [5, [6, 7]]]
    console.log(arr1.flat(1)) // [1, 2, 3, 4, 5, [6, 7]]
    console.log(arr1.flat(2)) // [1, 2, 3, 4, 5, 6, 7]
    複製代碼
  • 數組去重bash

    1. 利用對象(類map),以下
    function deleteArrayDuplicateElement (arr) {
      const mapObj = {}
      for (let i = 0; i < arr.length; i++) {
        if (mapObj[arr[i]]) {
          arr.splice(i, 1)
          i--
        } else {
          mapObj[arr[i]] = arr[i]
        }
      }
    }
    const testArr1 = [1, 2, 3, 3, 4, 6, 8, 8, 9]
    const testArr2 = [1, 2, 3, 3, 4, 6, 8, 8, 9, undefined, undefined, null, null]
    deleteArrayDuplicateElement(testArr1)
    console.log(testArr1) // [1, 2, 3, 4, 6, 8, 9]
    複製代碼

    Note: 該方法不能處理含有undefined,null重複值的數組,結果以下:優化

    deleteArrayDuplicateElement(testArr2);
    console.log(testArr2) // [1, 2, 3, 4, 6, 8, 9, undefined, undefined, null, null]
    複製代碼
    1. 利用Set
    Array.prototype.unique = function () {
      return [...new Set(this)];
    }
    const testArr1 = [1, 2, 3, 3, 4, 6, 8, 8, 9]
    console.log(testArr1.unique()) // [1, 2, 3, 4, 6, 8, 9]
    複製代碼

    Note: 該方法能夠處理含有undefined,null重複值的數組,結果以下ui

    const testArr2 = [1, 2, 3, 3, 4, 6, 8, 8, 9, undefined, undefined, null, null]
    console.log(testArr2.unique()) // [1, 2, 3, 4, 6, 8, 9, undefined, null]
    複製代碼
    1. 利用reduce
    // from https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
    
    let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
    let result = arr.sort().reduce((init, current) => {
        if(init.length === 0 || init[init.length-1] !== current) {
            init.push(current);
        }
        return init;
    }, []);
    console.log(result); //[1,2,3,4,5]  
    複製代碼
  • 實現array.filter方法this

    使用reduce實現spa

    const arrayFilter = function (fn, cxt) { 
       return cxt.reduce((pre, cur) => { 
         return fn(cur) ? [...pre, cur] : [...pre]
       }, [])
     }
     const arr3 = [1,2,3,4,5]
     function filter1 (ele) {
       return ele >= 3
     }
    console.log(arrayFilter(filter1, arr3)) // [3, 4, 5]
    console.log(arrayFilter(ele => ele >= 4, arr3))  // [4, 5]
    複製代碼
  • array.reduceprototype

    在上面的數組扁平化和去重中,都有基於reduce方法的實現方式。除此以外,reduce還能實現更多功能。code

    1. 計算數組裏全部值的和
    var total = [ 1, 2, 3, 4, 5 ].reduce(
        ( acc, cur ) => acc + cur,
        0
    );
    console.log(total) // 15
    複製代碼
    1. 累加對象數組裏的值
    var initialValue = 0;
    var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
      return accumulator + currentValue.x;
    },initialValue)
    
    console.log(sum) // 6
    複製代碼
    1. 將二維數組轉化爲一維
    var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
      ( acc, cur ) => acc.concat(cur),
      []
     );
    // flattened is [0, 1, 2, 3, 4, 5]
    複製代碼
    1. 計算數組中每一個元素出現的次數
    const names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
    const countedNames = names.reduce((allNames, name) => { 
      if (name in allNames) {
        allNames[name]++;
      } else {
        allNames[name] = 1;
      }
      return allNames;
    }, {});
    console.log(countedNames) // {Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}
    複製代碼
  • includes方法-判斷一個數組是否包含一個指定的值對象

    適用場景: 若是你有發現別人或本身有這樣寫if判斷條件時,可友善的提醒或者優化本身的代碼。 code示例:ip

    // ||的個數>=3
    if (code === '001' || code === '003' || code === '005' || code === '008') {
        // do something
    }
    複製代碼

    以上代碼段建議優化成以下,精簡代碼的同時提高代碼可讀性:

    if (['001', '003', '005', '008'].includes(code)) {
        // do something
    }
    複製代碼

歡迎在評論區留言提出補充點。 以爲有用的但願點贊支持下⊙∀⊙!

相關文章
相關標籤/搜索