add after ary assign assignIn assignInWith assignWith at before bind bindAll bindKey camelCase capitalize castArray ceil chain chunk clamp clone cloneDeep cloneDeepWith cloneWith compact concat conformsTo countBy create curry curryRight debounce deburr defaults defaultsDeep defer delay difference divide drop dropRight each eachRight endsWith entries entriesIn eq escape every extend extendWith fill filter find findIndex findKey findLast findLastIndex findLastKey first flatMap flatMapDeep flatMapDepth flatten flattenDeep flattenDepth flip floor forEach forEachRight forIn forInRight forOwn forOwnRight fromPairs functions functionsIn get groupBy gt gte has hasIn head inRange includes indexOf initial intersection invert invertBy invoke invokeMap isArguments isArray isArrayBuffer isArrayLike isArrayLikeObject isBoolean isBuffer isDate isElement isEmpty isEqual isEqualWith isError isFinite isFunction isInteger isLength isMap isMatch isMatchWith isNaN isNative isNil isNull isNumber isObject isObjectLike isPlainObject isRegExp isSafeInteger isSet isString isSymbol isTypedArray isUndefined isWeakMap isWeakSet join kebabCase keyBy keys keysIn last lastIndexOf lowerCase lowerFirst lt lte map mapKeys mapValues max maxBy mean meanBy memoize merge mergeWith min minBy multiply negate nth omit omitBy once orderBy overArgs pad padEnd padStart parseInt partial partialRight partition pick pickBy pull pullAll pullAllBy pullAllWith pullAt random rearg reduce reduceRight reject remove repeat replace rest result reverse round sample sampleSize set setWith shuffle size slice snakeCase some sortBy sortedIndex sortedIndexOf sortedLastIndex sortedLastIndexOf sortedUniq split spread startCase startsWith subtract sum sumBy tail take takeRight tap template throttle thru toArray toFinite toInteger toLength toLower toNumber toPairs toPairsIn toPlainObject toSafeInteger toString toUpper transform trim trimEnd trimStart truncate unary unescape union uniq uniqBy uniqWith unset unzip unzipWith update updateWith upperCase upperFirst values valuesIn without words wrap wrapperAt wrapperChain wrapperCommit wrapperFlatMap wrapperLodash wrapperNext wrapperPlant wrapperReverse wrapperToIterator wrapperValue xor zip zipObject zipObjectDeep zipWith

Lodash _.sumBy

Overview

The lodash method _.sumBy is a utility function that returns the sum of an array or object's numerical values. It iterates through each element in the collection, transforms the value using the provided iteratee function, and sums up the transformed values.

The function takes 2 parameters: the collection and the iteratee function. The collection can be either an array or an object. The iteratee function is optional and can be used to transform the values before they are summed up.

Here is the syntax for using _.sumBy:

_.sumBy(collection, [iteratee=_.identity])
  • collection: Array | Object - The collection to iterate over.
  • iteratee: Function - The function that accepts each value in the collection, transforms it, and returns the transformed value. This parameter is optional and defaults to _.identity which returns the original value unchanged.

Examples:

  1. Summing up an array of numbers:
const numbers = [5, 10, 15];
const sum = _.sumBy(numbers);

console.log(sum);
// Output: 30
  1. Summing up an array of objects by a specific property:
const expenses = [
  { type: 'rent', amount: 1000 },
  { type: 'groceries', amount: 500 },
  { type: 'rent', amount: 750 },
  { type: 'gas', amount: 80 }
];
const rentExpenses = _.sumBy(expenses, (expense) => {
  if (expense.type === 'rent') {
    return expense.amount;
  }
  return 0;
});

console.log(rentExpenses);
// Output: 1750
  1. Summing up values in an object:
const monthlyExpenses = {
  rent: 1000,
  groceries: 500,
  gas: 80
};

const sum = _.sumBy(monthlyExpenses);

console.log(sum);
// Output: 1580

In conclusion, _.sumBy is a simple and powerful utility function that makes it easy to sum up numerical values in arrays or objects. It's a handy tool for anyone working with collections of data in JavaScript.