intersectionWith.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var arrayMap = require('./_arrayMap'),
  2. baseIntersection = require('./_baseIntersection'),
  3. castArrayLikeObject = require('./_castArrayLikeObject'),
  4. last = require('./last'),
  5. rest = require('./rest');
  6. /**
  7. * This method is like `_.intersection` except that it accepts `comparator`
  8. * which is invoked to compare elements of `arrays`. Result values are chosen
  9. * from the first array. The comparator is invoked with two arguments:
  10. * (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 = rest(function(arrays) {
  28. var comparator = last(arrays),
  29. mapped = arrayMap(arrays, castArrayLikeObject);
  30. if (comparator === last(mapped)) {
  31. comparator = undefined;
  32. } else {
  33. mapped.pop();
  34. }
  35. return (mapped.length && mapped[0] === arrays[0])
  36. ? baseIntersection(mapped, undefined, comparator)
  37. : [];
  38. });
  39. module.exports = intersectionWith;