intersectionWith.js 1.4 KB

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