sumBy.js 908B

12345678910111213141516171819202122232425262728293031323334
  1. var baseIteratee = require('./_baseIteratee'),
  2. baseSum = require('./_baseSum');
  3. /**
  4. * This method is like `_.sum` except that it accepts `iteratee` which is
  5. * invoked for each element in `array` to generate the value to be summed.
  6. * The iteratee is invoked with one argument: (value).
  7. *
  8. * @static
  9. * @memberOf _
  10. * @since 4.0.0
  11. * @category Math
  12. * @param {Array} array The array to iterate over.
  13. * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
  14. * @returns {number} Returns the sum.
  15. * @example
  16. *
  17. * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
  18. *
  19. * _.sumBy(objects, function(o) { return o.n; });
  20. * // => 20
  21. *
  22. * // The `_.property` iteratee shorthand.
  23. * _.sumBy(objects, 'n');
  24. * // => 20
  25. */
  26. function sumBy(array, iteratee) {
  27. return (array && array.length)
  28. ? baseSum(array, baseIteratee(iteratee, 2))
  29. : 0;
  30. }
  31. module.exports = sumBy;