_.differenceWith(array, [values], [comparator])
6
_.differenceWith(array, [values], [comparator])
_.differenceWith方法和_.difference方法类似,都是求数组的差集,区别是_.differenceWith接收一个comparator参数作为比较元素值的方法。最终的结果数组取决于第一个参数array。comparator方法有两个参数,arrVal和OthVal。
参数
array (Array): 用来检查的数组
[values] (...Array): 用来排除的数组
[comparator] (Function): 比较array和values元素值的方法
返回值
(Array):返回一个包含过滤值的新数组
例子
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); // => [{ 'x': 2, 'y': 1 }]
源代码:
import baseDifference from './.internal/baseDifference.js' import baseFlatten from './.internal/baseFlatten.js' import isArrayLikeObject from './isArrayLikeObject.js' import last from './last.js' /** * This method is like `difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `pullAllWith`, this method returns a new array. * * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * const objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] * * differenceWith(objects, [{ 'x': 1, 'y': 2 }], isEqual) * // => [{ 'x': 2, 'y': 1 }] */ //类似difference方法,求数组的差集,区别是提供了comparator参数,是一个比较方法,在数组元素比较的时候用提供的comparator参数来比较 function differenceWith(array, ...values) { let comparator = last(values)//最后一个参数是comparator if (isArrayLikeObject(comparator)) {//如果比较器是一个array-like对象,就赋值为undefined comparator = undefined } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : [] //如果起始数组array不是array-like对象,就返回空数组 //如果是array-like对象,就调用baseDifference方法 //第一个参数是array起始数组,第二个参数是用来排除的数组values展开一层后的数组,第三个参数是迭代器赋值为undefined,第四个参数是比较器 } export default differenceWith
源码的其他部分和_.difference一样,这里省略