How to use the maxBy function from lodash

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

lodash.maxBy is a function that returns the maximum element of an array based on a given criterion.

106
107
108
109
110
111
112
113
114
115
116
  });
};


const addRegistrationToDoc = (doc, registrations) => {
  if (registrations.length) {
    const latest = _.maxBy(registrations, registration =>
      moment(registration.reported_date)
    );
    doc.registration_id = latest._id;
  }
fork icon181
star icon402
watch icon53

+ 2 other calls in file

254
255
256
257
258
259
260
261
262
263
module.exports.mapValues           = _.mapValues;
module.exports.mapcat              = _.mapcat;
module.exports.matches             = _.matches;
module.exports.matchesProperty     = _.matchesProperty;
module.exports.max                 = _.max;
module.exports.maxBy               = _.maxBy;
module.exports.mean                = _.mean;
module.exports.meanBy              = _.meanBy;
module.exports.memoize             = _.memoize;
module.exports.merge               = _.merge;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

How does lodash.maxBy work?

lodash.maxBy is a higher-order function that takes two arguments: a collection and an iteratee function. It returns the maximum element in the collection, based on the value returned by the iteratee function for each element. The iteratee function is called for each element in the collection to generate the value on which the maximum is determined, and the element with the highest value is returned.

33
34
35
36
37
38
39
40
41
42
43
44
function getBestPosition(positions) {
  if (positions.length === 0) {
    return {}
  }


  return maxBy(positions, p => getPositionPriority(p))
}


function buildNumero(numeroAdresses, {idVoieFantoir, codeCommune, forceCertification}) {
  const {numero, lieuDitComplementNom, lieuDitComplementNomAlt, parcelles, certificationCommune, codeAncienneCommune, nomAncienneCommune, dateMAJ} = numeroAdresses[0]
fork icon3
star icon7
watch icon3

168
169
170
171
172
173
174
175
176
177
  wifi: Math.min(Math.max(2*(100 - int(r.Status?.RSSI)), 0), 100), //See: https://stackoverflow.com/a/31852591/471136
  battery: int(r.Status?.Battery),
  temperature: int(r.Status?.Temperature),
  updatedAt: r?.Date?.length === 6 ? dayjs.utc(r.Date).subtract(1, 'month').toISOString() : undefined,
}}).filter(status => status.wifi && status.battery && status.temperature && status.updatedAt)
const latest = _.maxBy(statuses, r => dayjs(r.updatedAt))
if (latest) {
  log.debug(`Updating db status for deviceId=${device.id} to`, latest)
  db.devices.updateStatus(device.id, latest)
} else {
fork icon0
star icon28
watch icon1

+ 10 other calls in file

Ai Example

1
2
3
4
5
6
7
8
const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 20 },
];

const oldestUser = _.maxBy(users, "age");
console.log(oldestUser); // Output: { name: 'Bob', age: 30 }

In this example, lodash.maxBy is used to find the object with the maximum age property in the users array. The function takes two arguments: the array to search and the property to compare. It returns the object with the maximum value for the specified property. In this case, it returns the object with name "Bob" and age 30.

548
549
550
551
552
553
554
555
556
557
558
559
560
console.log(floor); // => 4


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


const maxBy = _.maxBy([{ 'n': 1 }, { 'n': 2 }], o => o.n);
console.log(maxBy); // => { 'n': 2 }


const mean = _.mean([4, 2, 8, 6]);
console.log(mean); // => 5
fork icon0
star icon4
watch icon0

+ 15 other calls in file

322
323
324
325
326
327
328
329
330
331
  if (ownerVotes.length) winningFields[id] = getSingleFieldsDisplay(_.maxBy(ownerVotes, 'adminVote.timestamp'));
  else if (adminVotes.length) winningFields[id] = getSingleFieldsDisplay(_.maxBy(adminVotes, 'adminVote.timestamp'));
  else winningFields[id] = getSingleFieldsDisplay(_.maxBy(approvedFields, 'adminVote.timestamp'));
  continue;
}
const heaviestField = _.maxBy(groupedFields[id], (field) => {
  if (_.get(field, 'adminVote.status') !== 'rejected' && field.weight > 0
      && field.approvePercent > MIN_PERCENT_TO_SHOW_UPGATE) return field.weight;
});
if (heaviestField) winningFields[id] = getSingleFieldsDisplay(heaviestField);
fork icon0
star icon3
watch icon3

510
511
512
513
514
515
516
517
518
519
if (_.includes(selectedFields, 'status-label')) {
  deviceInfo.push(device.status.label);
}

if (device.mmtune) {
  var best = _.maxBy(device.mmtune.scanDetails, function(d) {
    return d[2];
  });

  if (_.includes(selectedFields, 'freq')) {
fork icon0
star icon1
watch icon1

+ 3 other calls in file

630
631
632
633
634
635
636
637
638
639
    }
}
else{
    
    for(const item in raw_group){
        const invoice = _.maxBy(raw_group[item], o => o.tariff.tariff_rate)
        //get conditions
        let conditions = allConditions.filter(item => item.agg_id === invoice.tariff.fk_agg_id)
        
        //convert the paremeters into array
fork icon0
star icon0
watch icon2

+ 17 other calls in file

32
33
34
35
36
37
38
39
40
41
if (groupedKey === 'undefined') {
  uniqueProducts.push(...grouped[groupedKey]);
  continue;
}
if (grouped[groupedKey].length > 1) {
  const latest = _.maxBy(grouped[groupedKey], 'dateUpdated');
  let parentAsin = _.find(
    latest.features,
    (f) => _.includes(PARENT_ASIN_FIELDS, f.key),
  );
fork icon0
star icon0
watch icon1

+ 5 other calls in file

333
334
335
336
337
338
339
340
341
let recordPoint = find( examination.$extention.recordPoints, r => r.id == record.parentId)

let formRecords = examination.$extention.forms.map( f => {
  let res = extend({}, f)
  res.examinationId = examination.id
  let key = maxBy(keys(f.data))
  res.data = res.data[key]
  return res 
})
fork icon0
star icon0
watch icon1

+ 2 other calls in file

32
33
34
35
36
37
38
39
40
41
42
      author: authorName,
      likes: _.sumBy(author, 'likes')
    }))
    .value()
  
  return _.maxBy(authorLikes, (author) => author.likes)
}


module.exports = {
  dummy,
fork icon0
star icon0
watch icon2

+ 5 other calls in file

34
35
36
37
38
39
40
41
42
43
44
    ? undefined
    : most()
}


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

+ 5 other calls in file

28
29
30
31
32
33
34
35
36
37
38
39
}


const mostBlogs = (blogs) => {
  const counts = _.countBy(blogs, 'author')
  const countsAsTuples = _.entries(counts)
  const maxTuple = _.maxBy(countsAsTuples, _.last)


  if(maxTuple === undefined){
    return undefined
  }
fork icon0
star icon0
watch icon1

126
127
128
129
130
131
132
133
134
135

if (mean && _.isNumber(mean)) {
  details.mean = mean;
}

var mostRecent = _.maxBy(sgvs, 'mills');

if (mostRecent) {
  details.last = mostRecent.mgdl;
  details.mills = mostRecent.mills;
fork icon0
star icon0
watch icon0

10
11
12
13
14
15
16
17
18
19
20
  const mostLikedBlogFiltered = _.pick(mostLikedBlog, ['title', 'author', 'likes']);
  return [mostLikedBlog, mostLikedBlogFiltered];
};


const mostBlogs = (inputBlogs) => {
  const { author } = _.maxBy(inputBlogs, 'author');
  const blogsCount = _.countBy(inputBlogs, 'author');
  const blogs = _.max(Object.values(blogsCount));
  return { author, blogs };
};
fork icon0
star icon0
watch icon0

65
66
67
68
69
70
71
72
73
74
// Group blogs by author -> object where key = author name, value = array of blogs written by that author
const authorLikes = lodash.groupBy(blogs, 'author')
// Map over grouped blogs, calculate total number of likes each author has received -> object where key = author name and value = total number of likes received
const authorLikesTotal = lodash.mapValues(authorLikes, blogs => lodash.sumBy(blogs, 'likes'))
// Find author with most likes. maxBy takes array of keys (author names) and a function that returns the value to compare (likes of that author)
const maxLikesAuthor = lodash.maxBy(lodash.keys(authorLikesTotal), author => authorLikesTotal[author])
// Finally, total likes of author with most likes
const maxLikesCount = authorLikesTotal[maxLikesAuthor]

return blogs.length === 0
fork icon0
star icon0
watch icon0

28
29
30
31
32
33
34
35
36
37
38
    return {
      author: authorName,
      blogs: nbBlog,
    };
  });
  return _.maxBy(formatedJson, (unit) => unit.blogs);
}


function authorWithMostLikes(arrList) {
  const authors = _.countBy(arrList, (unit) => unit.author);
fork icon0
star icon0
watch icon0

30
31
32
33
34
35
36
37
38
39
40
    const sorted = Object.entries(_.groupBy(blogs, 'author'))
    const likes = []
    sorted.forEach(element => {
        likes.push({ author: element[0], likes: _.sumBy(element[1], 'likes') })
    });
    return _.maxBy(likes, 'likes')
}


module.exports = {
    dummy,
fork icon0
star icon0
watch icon0

23
24
25
26
27
28
29
30
31
32
33
const mostBlogs = (blogs) => {
  const authorCounts = _.countBy(blogs, (b) => b.author)
  const authorFrequencies = Object.keys(authorCounts).map(key => { 
    return { author: key, blogs: authorCounts[key] }
  })
  return _.maxBy(authorFrequencies, 'blogs')
}


const mostLikes = (blogs) => {
  const authorBlogs = _.groupBy(blogs, 'author')
fork icon0
star icon0
watch icon0

+ 3 other calls in file

59
60
61
62
63
64
65
66
67
68
69
const getList = files => {
	const raws = files.map( f => extend(f, { path: getPath(files,f) }))
	const pathes = uniqBy(raws, "path").map( d => d.path)
	let res = []
	pathes.forEach( p => {
		res.push( maxBy(raws.filter(r => r.path == p), "modifiedTime"))
	})
	return res


}	
fork icon0
star icon0
watch icon0

Other functions in lodash

Sorted by popularity

function icon

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