天天一個lodash方法-differenceWith

differenceWith

用法

_.differenceBy(array, [values], [iteratee=_.identity])api

做用

與difference相比,多了一個compator(我這裏叫它比較器),數組

demo

仍是看官方api給的demoide

var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
 
_.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);

源碼部分

baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)

第三個參數對應的是iteratee,在differenceWith傳入的是undefined函數

下邊的函數我delete掉不會執行的部分。code

function baseDifference(array, values, iteratee, comparator) {
  var index = -1,
      includes = arrayIncludes,
      isCommon = true,
      length = array.length,
      result = [],
      valuesLength = values.length;

 
  if (comparator) {
    includes = arrayIncludesWith;
    isCommon = false;
  }
  
  outer:
  while (++index < length) {
    var value = array[index],
        computed = iteratee == null ? value : iteratee(value);

    value = (comparator || value !== 0) ? value : 0;
   
    if (!includes(values, computed, comparator)) {
      result.push(value);
    }
  }
  return result;
}

兩個數組去除交集,固然免不了循環比較。只有符合某種條件,纔會push到咱們的結果集合中。符合條件的函數的判斷在baseDifference是下段代碼接口

!includes(values, computed, comparator)

咱們先分析三個參數,values是須要排除的數組,computed是被檢查數組中的某個元素;comparator是每一個傳入的校驗器。源碼

咱們須要的結果,computed和迭代中values的元素,經過comparator處理,若是符合比較條件,返回true,不然返回flase。it

for(let i=0;i<values.length;i++){
    if(comparator(comuted,values[i])){
        return true
    }
    return false
}

如今能夠回看arrayIncludeWith源碼了io

function arrayIncludesWith(array, value, comparator) {
  var index = -1,
      length = array == null ? 0 : array.length;

  while (++index < length) {
    if (comparator(value, array[index])) {
      return true;
    }
  }
  return false;
}

實現的功能是一致的。function

上邊的demo恰好沒給輸出結果,看了這麼多,必定知道結果是[ { 'x': 2, 'y': 1 }]

comparator做爲一個比較器,它接口兩個參數,一個是檢查的數組中的元素,和排除的數組中的元素,是否符合某個判斷條件。而不是單純的值判斷去重。固然你也能夠傳入一個以下的函數,它依然是一個值判斷

function comparator(o,n){
 return o == n
}
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
 
_.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
// =>[ { 'x': 2, 'y': 1 }]
相關文章
相關標籤/搜索