How to use the sumBy function from lodash

Find comprehensive JavaScript lodash.sumBy code examples handpicked from public code repositorys.

lodash.sumBy is a function that iterates through an array of objects, applies a function to each element to retrieve a numeric value, and returns the sum of all those numeric values.

2031
2032
2033
2034
2035
2036
2037
2038
2039

generateStats(stats) {
  const result = {}
  for (const metric in stats) {
    result[metric] = stats[metric]
    result['total' + metric[0].toUpperCase() + metric.slice(1) ] = _.sumBy(stats[metric], 1)
  }
  return result
}
fork icon117
star icon456
watch icon48

+ 12 other calls in file

367
368
369
370
371
372
373
374
375
376
module.exports.strContains         = _.strContains;
module.exports.stripTags           = _.stripTags;
module.exports.sub                 = _.sub;
module.exports.subtract            = _.subtract;
module.exports.sum                 = _.sum;
module.exports.sumBy               = _.sumBy;
module.exports.tail                = _.tail;
module.exports.take                = _.take;
module.exports.takeRight           = _.takeRight;
module.exports.takeRightWhile      = _.takeRightWhile;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.sumBy work?

lodash.sumBy is a method in the Lodash library that takes a collection of objects and a function that returns a numeric value for each object, and returns the sum of those numeric values for all objects in the collection.

It first maps each object in the collection to a numeric value by applying the given function to each object, then calculates the sum of those numeric values using the lodash.sum function.

606
607
608
609
610
611
612
613
614
615
616
  var address = privateKey.publicKey.toAddress();
  self.getUtxos({
    addresses: coin == 'bch' ? address.toLegacyAddress() : address.toString(),
  }, function(err, utxos) {
    if (err) return cb(err);
    return cb(null, _.sumBy(utxos, 'satoshis'));
  });
};


API.prototype.buildTxFromPrivateKey = function(privateKey, destinationAddress, opts, cb) {
fork icon9
star icon0
watch icon0

575
576
577
578
579
580
581
582
583
584
585
586
587
588
console.log(subtract); // => 2


const sum = _.sum([4, 2, 8, 6]);
console.log(sum); // => 20


const sumBy = _.sumBy([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], o => o.n);
console.log(sumBy); // => 20




// Number
fork icon0
star icon4
watch icon0

+ 15 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
const _ = require("lodash");

const orders = [
  { product: "t-shirt", price: 15 },
  { product: "pants", price: 25 },
  { product: "socks", price: 5 },
];

const totalPrice = _.sumBy(orders, (order) => order.price);

console.log(totalPrice); // output: 45

In this example, lodash.sumBy is used to calculate the total price of all the orders in the orders array by summing the price property of each order object.

360
361
362
363
364
365
366
367
368
369

$scope.sumHaettavaAvustus = function () {
  var avustuskohteet = _.flatten(_.map($scope.avustuskohdeluokat, function (l) {
    return l.avustuskohteet;
  }));
  return _.sumBy(avustuskohteet, _.partial(h.avustuskohdeRahamaara, 'haettavaavustus'));
};

$scope.sumHaettavaElyAvustus = function () {
  var maararahatarpeetSum =
fork icon2
star icon0
watch icon0

+ 2 other calls in file

729
730
731
732
733
734
735
736
737
  var currentJobs = _.filter(this.jobTimerList(), function(d) { 
    var docDate = moment(d.date())
    return momentValue.isSame(docDate, 'month')
  });

  var monthTimeSum = _.sumBy(currentJobs, function(o) { return o.elapsedSeconds(); });

  footer.overtimeSubject.next(monthTimeSum-(daysUntilToday*8*60*60))
}
fork icon1
star icon1
watch icon2

+ 47 other calls in file

354
355
356
357
358
359
360
361
362
363
responsive: true,
drawCallback: async function () {
    var api = this.api();
    var columns = api.columns( [1,5],  {"filter": "applied"} ).data()
    var zippedColumns = _.zipWith(columns[0], columns[1], (a,b) => {return {description: a, duration: b}})
    var sumTableHours = _.sumBy(zippedColumns, function(element){
        if (element.description == "Abwesend") {
            return 0;
        }
        var duration = element.duration
fork icon1
star icon1
watch icon2

+ 15 other calls in file

101
102
103
104
105
106
107
108
109
110
  !_.isEmpty(blacklist)
  && !_.isEmpty(field.active_votes)
 && field.name !== FIELDS_NAMES.AUTHORITY
) {
  field.active_votes = _.filter(field.active_votes, (o) => !_.includes(blacklist, o.voter));
  field.weight = 1 + _.sumBy(field.active_votes, (vote) => vote.weight);
}
let adminVote, administrativeVote, ownershipVote, ownerVote;
_.map(field.active_votes, (vote) => {
  vote.timestamp = vote._id.getTimestamp().valueOf();
fork icon0
star icon3
watch icon3

+ 2 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26
const sumQtyHeader = ({data,field})=>{
    return parseFloat(_.sum(data.map(item => parseFloat(item[field])))).toFixed(2)
}


const sumBy = ({data,field}) => {
    return _.sumBy(data,item => parseFloat(item[field])).toFixed(2)
}


const getAggCondition = async(aggId)=>{
    try{
fork icon0
star icon0
watch icon2

+ 17 other calls in file

591
592
593
594
595
596
597
598
599
600
return await Promise.all(
  allUserMonthData.map(async (item, index) => {
    if (item.userId) {
      const data = await memberData(type, item.userId._id);

      const total = _.sumBy(data, 'amount');
      if (data.length > 0) {
        return {
          userId: item.userId._id,
          name: item.userId.name,
fork icon0
star icon0
watch icon1

+ 11 other calls in file

28
29
30
31
32
33
34
35
36
37

const authorLikes = _(blogs)
  .groupBy('author')
  .map((author, authorName) => ({
    author: authorName,
    likes: _.sumBy(author, 'likes')
  }))
  .value()

return _.maxBy(authorLikes, (author) => author.likes)
fork icon0
star icon0
watch icon2

173
174
175
176
177
178
179
180
181
];
const expectedCost = _(combinedArray)
  .groupBy("activity")
  .map((combined, id) => ({
    activity: id,
    total: _.sumBy(combined, "total"),
  }))
  .value();
// console.log(expectedCost)
fork icon0
star icon0
watch icon1

+ 219 other calls in file

552
553
554
555
556
557
558
559
560
561
  search.map((item) => _.sumBy(item.fifth, 'qtyord'))
);
const totalItems9 = _.sumBy(
  search.map((item) => _.sumBy(item.fourth, 'qtyord'))
);
const totalItems10 = _.sumBy(
  search.map((item) => _.sumBy(item.third, 'qtyord'))
);
const totalItems11 = _.sumBy(
  search.map((item) => _.sumBy(item.second, 'qtyord'))
fork icon0
star icon0
watch icon1

+ 174 other calls in file

27
28
29
30
31
32
33
34
35
36
    basicSalary,
    overTimeRatePerHr : isNaN(overTimeRatePerHr) ? 0 : overTimeRatePerHr,
    allowances: validateAllowanceAndDeductionsModel(allowances || []),
    deductions: validateAllowanceAndDeductionsModel(deductions || []),
};
salaryObj.allowances.length > 0 ? salaryObj['totalAllowance'] = sumBy(salaryObj.allowances, 'amount') : 0;
salaryObj.deductions.length > 0 ? salaryObj['totalDeductions'] = sumBy(salaryObj.deductions, 'amount') : 0;
salaryObj['netSalary'] = salaryObj['basicSalary'] + salaryObj['totalAllowance'] - salaryObj['totalDeductions'];

const newSalary = await salary.create(salaryObj);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

832
833
834
835
836
837
838
839
840
841
  // return value+= value;
return value.meteors
 });
 
console.log("New Array",newarr1)
let ttl = _.sumBy([...newarr1]);
console.log("rTotal",ttl);
//console.log("getdatail",getdatail)
 
 let ttll  = ttl+10
fork icon0
star icon0
watch icon3

+ 2 other calls in file

42
43
44
45
46
47
48
49
50
51
const mostLikesBlogs = (blogs) => {
    const groupedBlogs = _.groupBy(blogs, 'author')
    const authorCounts = _.map(groupedBlogs, (blogs, author) => {
        return {
            author,
            count: _.sumBy(blogs, 'likes'),
        }
    })
    const sortedAuthorCounts = _.orderBy(authorCounts, 'count', 'desc')
    const mostProlificAuthor = sortedAuthorCounts[0]
fork icon0
star icon0
watch icon1

+ 2 other calls in file

56
57
58
59
60
61
62
63
64
65
  { users: { $elemMatch: { permlink: paymentData.reservationPermlink } } },
);
if (_.get(campaign, 'compensationAccount')) {
  await updateCompensationFee(paymentData, campaign, _.round(voteWeight / 2, 3));
}
const amount = _.sumBy(result, 'amount');
if (voteWeight >= amount) {
  voteWeight = amount;
  payed = true;
}
fork icon0
star icon0
watch icon1

+ 5 other calls in file

36
37
38
39
40
41
42
43
44
45
46
}


const mostLikes = (blogs) => {
  const most = _.maxBy(_(blogs).groupBy('author').map(group => ({
    author: group[0].author,
    likes: _.sumBy(group, 'likes')
  })).value(), 'likes')
  return blogs === undefined
    ? undefined
    : most
fork icon0
star icon0
watch icon1

+ 2 other calls in file

15
16
17
18
19
20
21
22
23
24

let transaction = new smartCash.TransactionBuilder();

let listUnspent = await getUnspent(fromAddress);

let totalUnspent = _.sumBy(listUnspent, 'amount');

console.log(`Total Unspent ${totalUnspent}`)

let fee = calculateFee(listUnspent);
fork icon0
star icon0
watch icon3

370
371
372
373
374
375
376
377
378
379
380
381
// console.log(lodash.random(5, 1, true), "randomNumber");
// console.log(lodash.random(1.2), "randomCheckrd");


// var objects = [{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }];


// const sum = lodash.sumBy(objects, (o) => {
//   return o.n;
// });
// const sum = lodash.sumBy(objects, "n");
// console.log(sum, "sum");
fork icon0
star icon0
watch icon0

+ 9 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)