How to use the sortBy function from lodash

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

lodash.sortBy is a method that sorts an array of objects based on a specified key or keys in ascending or descending order.

53
54
55
56
57
58
59
60
61
62

export function sortByLengthOfArrayProperty(array, propertyName) {
  function arrayLengthComparator(item) {
    return item[propertyName] ? item[propertyName].length : 0;
  }
  return _.sortBy(array, arrayLengthComparator);
}

export function groupWithCounts(array) {
  const counts = {};
fork icon942
star icon0
watch icon2

+ 3 other calls in file

5
6
7
8
9
10
11
12
13
14
async function main() {
  logger.info(`loading streams...`)
  await db.streams.load()

  let streams = await db.streams.find({})
  streams = _.sortBy(streams, 'channel')
  streams = streams.map(stream => {
    let data = {
      channel: stream.channel,
      url: stream.url,
fork icon426
star icon0
watch icon0

How does lodash.sortBy work?

lodash.sortBy is a method that sorts an array of objects based on a specified key or keys in ascending or descending order. The method takes two arguments: the array to sort and the key or keys to sort by. The key or keys can be a string representing a property of the objects in the array to sort by, or they can be a function that returns the value to sort by. By default, lodash.sortBy sorts the array in ascending order. To sort in descending order, you can specify the key or keys as an array and prepend a - sign to the keys that should be sorted in descending order. For example, the following code sorts an array of objects representing people by their age in ascending order: javascript Copy code {{{{{{{ const _ = require('lodash'); const people = [ { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }, { name: 'Charlie', age: 20 }, ]; const sortedPeople = _.sortBy(people, 'age'); console.log(sortedPeople); In this code, we use lodash.sortBy to sort the people array by the age property of each object. The resulting sorted array is stored in the sortedPeople variable, and is then logged to the console using console.log(). The output of this code will be: yaml Copy code {{{{{{{ class="!whitespace-pre hljs language-yaml">[ { name: 'Charlie', age: 20 }, { name: 'Alice', age: 25 }, { name: 'Bob', age: 30 } ] Overall, lodash.sortBy provides a simple and convenient way to sort an array of objects based on a specified key or keys in ascending or descending order, making it easier to work with complex data structures in JavaScript.

175
176
177
178
179
180
181
182
183
184
let contractLocations = {};
let shallowestContracts = {};

linked[CONTRACTMAP_KEY] = {};

var sourcePairs = _.sortBy(_.pairs(importerMap),
                           (pair) => depths[pair[0]]);

for (let sourcePair of sourcePairs) {
  let path = sourcePair[0];
fork icon65
star icon1
watch icon3

+ 3 other calls in file

4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
*  to create a "_.pluck" or "_.where" style callback, respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Array} Returns a new array of sorted elements.
* @example
*
* _.sortBy([1, 2, 3], function(num) { return Math.sin(num); });
* // => [3, 1, 2]
*
* _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math);
* // => [3, 1, 2]
fork icon73
star icon711
watch icon29

+ 5 other calls in file

Ai Example

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

const users = [
  { name: "Alice", age: 25 },
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 20 },
];

const sortedUsers = _.sortBy(users, "age");

console.log(sortedUsers);

In this example, we have an array of users objects, each of which has a name and age property. We use lodash.sortBy to sort the users array based on the age property of each object. The resulting sorted array is stored in the sortedUsers variable, and is then logged to the console using console.log(). The output of this code will be: yaml Copy code

1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
    obj.factsRank,
    obj.pageRankLinksRank
  ]
  obj.totalRank = lodash.sum(lodash.sortBy(top3).slice(0, 3))
})
objects = lodash.sortBy(objects, ["totalRank"])

const ranks = {}
objects.forEach((obj, index) => {
  obj.index = index
fork icon73
star icon647
watch icon6

+ 31 other calls in file

123
124
125
126
127
128
129
130
131
132
const silenceFor = date.getDuration(config.silence_for);

for (let i = 0; i < registrations.length; i++) {
  const registration = registrations[i];
  if (registration.scheduled_tasks && registration.scheduled_tasks.length) {
    const scheduledTasks = _.sortBy(registration.scheduled_tasks, 'due');
    // if the visit was reported prior to the the most recent scheduled task
    // we move to the next registration because the visit does not get
    // associated to anything: no reminder messages have been sent yet OR
    // visit is not responding to a reminder (in this case, existing functionality
fork icon181
star icon402
watch icon53

+ 2 other calls in file

346
347
348
349
350
351
352
353
354
355
module.exports.slugify             = _.slugify;
module.exports.snakeCase           = _.snakeCase;
module.exports.snapshot            = _.snapshot;
module.exports.sneq                = _.sneq;
module.exports.some                = _.some;
module.exports.sortBy              = _.sortBy;
module.exports.sortedIndex         = _.sortedIndex;
module.exports.sortedIndexBy       = _.sortedIndexBy;
module.exports.sortedIndexOf       = _.sortedIndexOf;
module.exports.sortedLastIndex     = _.sortedLastIndex;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

68
69
70
71
72
73
74
75
76
77
78
    if (this.folderCache[folderPath]) return this.folderCache[folderPath]
    const files = this.list(folderPath)
      .filter(file => file.endsWith(SCROLL_FILE_EXTENSION))
      .map(filePath => this.getScrollFile(filePath))


    this.folderCache[folderPath] = lodash.sortBy(files, file => file.timestamp).reverse()
    return this.folderCache[folderPath]
  }
}

fork icon12
star icon315
watch icon0

1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
 * @param {Array} prizeSets the first PrizeSet Array
 * @param {Array} otherPrizeSets the second PrizeSet Array
 * @returns {Boolean} true if different, false otherwise
 */
function isDifferentPrizeSets(prizeSets = [], otherPrizeSets = []) {
  return !_.isEqual(_.sortBy(prizeSets, "type"), _.sortBy(otherPrizeSets, "type"));
}


/**
 * Validate the winners array.
fork icon45
star icon17
watch icon0

486
487
488
489
490
491
492
493
494
495
    const folder = new ScrollFolder(folderPath)
    folder.relativePath = relativePath + "/"
    arr = arr.concat(folder.getGroup(group))
  })

  return lodash.sortBy(arr, file => file.timestamp).reverse()
}

get grammarErrors() {
  this._initFiles() // Init all compilers
fork icon12
star icon314
watch icon8

1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
    })
}


self.bestlist = function(){
    var nodes = _.sortBy(self.initednodes(), function(node){
        return -node.statistic.probability()
    })

    var ns = _.filter(nodes, function(n, i){
fork icon33
star icon58
watch icon7

+ 15 other calls in file

1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
        }
        srs['probab'] = Object.values(labelCase).sort((x,y)=> y-x);
    }
}
//sort the max-uncertain Ascending
tickets = await _.sortBy(tickets, 'probab');
let ticketsGrop = await _.groupBy(tickets, 'probab[0]');
const annotationNum = Object.keys(ticketsGrop)[0];

let temp = [];
fork icon15
star icon37
watch icon8

+ 3 other calls in file

317
318
319
320
321
322
323
324
325
326
      else entry[sexGenderKey].cases = count
    }
  })
Object.keys(toAdd).forEach(id => {
  const file = this.folder.getFile(id)
  const sorted = lodash.sortBy(toAdd[id], "sex", row => parseInt(row.age))
  const tree = new TreeNode(sorted)
  if (!file.has("uscsTable"))
    file.appendLineAndChildren("uscsTable 2019", tree.toDelimited("|"))
  const deaths = lodash.sum(
fork icon12
star icon22
watch icon5

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
if (err) {
  logger.error(JSON.stringify(err));
  return h.response(err).code(err.code);
}
if (classes.length > 0) {
  classes = _.sortBy(classes, 'start_time');
}
if (classes.length > 4) {
  classes = classes.slice(0, 4);
}
fork icon18
star icon15
watch icon4

+ 2 other calls in file

488
489
490
491
492
493
494
495
496
  rolesList: _.map(roles, (r) => r.role),
  ...userInfo,
});


transforms.pathway = ({ milestones, ...pathwayInfo }) => ({
  milestones: _.sortBy(milestones, (m) => m.position),
  ...pathwayInfo,
});
fork icon18
star icon15
watch icon4

+ 3 other calls in file

621
622
623
624
625
626
627
628
629
630
  if (url?.endsWith('-tag')) return 'tl';
  return 'en';
};

// sort a list of objects by a certain property in the object
liquid.filters.sortObjectsBy = (entities, path) => _.sortBy(entities, path);

liquid.filters.getValueFromObjPath = (obj, path) => _.get(obj, path);

// get a value from a path of an object in an array
fork icon7
star icon15
watch icon0

+ 2 other calls in file

3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646


  throw new Error('Unknown error in getUnsortedOptions');
}
function getOptions(fieldConfig, injected) {
  var unsortedOptions = getUnsortedOptions(fieldConfig, injected);
  return fieldConfig.sorted ? lodash.sortBy(unsortedOptions, 'name') : unsortedOptions;
}
function renderValue(fieldConfigPartial, model) {
  var fieldConfig = fillInFieldConfig(fieldConfigPartial),
      field = fieldConfig.field,
fork icon3
star icon15
watch icon0

53
54
55
56
57
58
59
60
61
62
63
64
    new Transform({objectMode: true, transform: prepareData})
  ))


  await sourcePartUpdater.save()


  return sortBy(adresses, 'idAdresse')
}


module.exports = importData
fork icon3
star icon7
watch icon3

183
184
185
186
187
188
189
190
191
192
    phaseGroups[p.phase_type_id] = []
  }
  phaseGroups[p.phase_type_id].push(p)
})
_.forEach(_.cloneDeep(phaseGroups), (pg, pt) => {
  phaseGroups[pt] = _.sortBy(pg, 'scheduled_start_time')
})

for (const key of _.keys(phaseGroups)) {
  let phaseOrder = 0
fork icon6
star icon3
watch icon35

+ 7 other calls in file

2
3
4
5
6
7
8
9
10
11
12
13


// 12.toString(2) => 1100
// parseInt("1100", 2) => 12


module.exports = {
  sort: arr => _.sortBy(arr, x=>x),
  // fixes headache in past due to arr.map(parseInt) applying parseInt(element, index, array)
  // Ooh this would be same as _.ary(parseInt, 1)
  int: s => parseInt(s, 10),
  // faster to type and return starting value. I would use log except it looks too much like Math.log
fork icon1
star icon4
watch icon0

+ 2 other calls in file

Other functions in lodash

Sorted by popularity

function icon

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