UNPKG

1.39 kBJavaScriptView Raw
1import arrayMap from './_arrayMap.js';
2import baseIntersection from './_baseIntersection.js';
3import baseRest from './_baseRest.js';
4import castArrayLikeObject from './_castArrayLikeObject.js';
5import last from './last.js';
6
7/**
8 * This method is like `_.intersection` except that it accepts `comparator`
9 * which is invoked to compare elements of `arrays`. The order and references
10 * of result values are determined by the first array. The comparator is
11 * invoked with two arguments: (arrVal, othVal).
12 *
13 * @static
14 * @memberOf _
15 * @since 4.0.0
16 * @category Array
17 * @param {...Array} [arrays] The arrays to inspect.
18 * @param {Function} [comparator] The comparator invoked per element.
19 * @returns {Array} Returns the new array of intersecting values.
20 * @example
21 *
22 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
23 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
24 *
25 * _.intersectionWith(objects, others, _.isEqual);
26 * // => [{ 'x': 1, 'y': 2 }]
27 */
28var intersectionWith = baseRest(function(arrays) {
29 var comparator = last(arrays),
30 mapped = arrayMap(arrays, castArrayLikeObject);
31
32 comparator = typeof comparator == 'function' ? comparator : undefined;
33 if (comparator) {
34 mapped.pop();
35 }
36 return (mapped.length && mapped[0] === arrays[0])
37 ? baseIntersection(mapped, undefined, comparator)
38 : [];
39});
40
41export default intersectionWith;