intersectionBy.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. var arrayMap = require('./_arrayMap'),
  2. baseIntersection = require('./_baseIntersection'),
  3. baseIteratee = require('./_baseIteratee'),
  4. baseRest = require('./_baseRest'),
  5. castArrayLikeObject = require('./_castArrayLikeObject'),
  6. last = require('./last');
  7. /**
  8. * This method is like `_.intersection` except that it accepts `iteratee`
  9. * which is invoked for each element of each `arrays` to generate the criterion
  10. * by which they're compared. The order and references of result values are
  11. * determined by the first array. The iteratee is invoked with one argument:
  12. * (value).
  13. *
  14. * @static
  15. * @memberOf _
  16. * @since 4.0.0
  17. * @category Array
  18. * @param {...Array} [arrays] The arrays to inspect.
  19. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  20. * @returns {Array} Returns the new array of intersecting values.
  21. * @example
  22. *
  23. * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
  24. * // => [2.1]
  25. *
  26. * // The `_.property` iteratee shorthand.
  27. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
  28. * // => [{ 'x': 1 }]
  29. */
  30. var intersectionBy = baseRest(function(arrays) {
  31. var iteratee = last(arrays),
  32. mapped = arrayMap(arrays, castArrayLikeObject);
  33. if (iteratee === last(mapped)) {
  34. iteratee = undefined;
  35. } else {
  36. mapped.pop();
  37. }
  38. return (mapped.length && mapped[0] === arrays[0])
  39. ? baseIntersection(mapped, baseIteratee(iteratee, 2))
  40. : [];
  41. });
  42. module.exports = intersectionBy;