unionBy.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var baseFlatten = require('./_baseFlatten'),
  2. baseIteratee = require('./_baseIteratee'),
  3. baseUniq = require('./_baseUniq'),
  4. isArrayLikeObject = require('./isArrayLikeObject'),
  5. last = require('./last'),
  6. rest = require('./rest');
  7. /**
  8. * This method is like `_.union` except that it accepts `iteratee` which is
  9. * invoked for each element of each `arrays` to generate the criterion by
  10. * which uniqueness is computed. The iteratee is invoked with one argument:
  11. * (value).
  12. *
  13. * @static
  14. * @memberOf _
  15. * @since 4.0.0
  16. * @category Array
  17. * @param {...Array} [arrays] The arrays to inspect.
  18. * @param {Array|Function|Object|string} [iteratee=_.identity]
  19. * The iteratee invoked per element.
  20. * @returns {Array} Returns the new array of combined values.
  21. * @example
  22. *
  23. * _.unionBy([2.1], [1.2, 2.3], Math.floor);
  24. * // => [2.1, 1.2]
  25. *
  26. * // The `_.property` iteratee shorthand.
  27. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
  28. * // => [{ 'x': 1 }, { 'x': 2 }]
  29. */
  30. var unionBy = rest(function(arrays) {
  31. var iteratee = last(arrays);
  32. if (isArrayLikeObject(iteratee)) {
  33. iteratee = undefined;
  34. }
  35. return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), baseIteratee(iteratee));
  36. });
  37. module.exports = unionBy;