_.differenceBy(array, [values], [iteratee=_.identity])
复制代码
和_.difference方法很像只不过多提供了一个iteratee参数,能够让你在遍历的时候做一些自定义的事情。主要还是用根据第二个数组去掉第一个数组中的值。
使用示例
_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [1.2]
// The `_.property` iteratee shorthand.
_.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
// => [{ 'x': 2 }]
复制代码
源码解析
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 `iteratee` which
* is invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* **Note:** Unlike `pullAllBy`, 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} iteratee The iteratee invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor)
* // => [1.2]
*/
function differenceBy(array, ...values) {
let iteratee = last(values)
if (isArrayLikeObject(iteratee)) {
iteratee = undefined
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), iteratee)
: []
}
export default differenceBy
复制代码
和_.difference方法基本上一样,但是多提供了一个iteratee参数,这个参数可以在比较前先做一个处理(对第一和第二个参数的数组遍历处理)。