How to use the orderBy function from lodash

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

lodash.orderBy is a JavaScript function that sorts an array of objects based on one or more of their properties, using a specified order and sorting direction.

191
192
193
194
195
196
197
198
199
200
			brew.tags].join('\n')
			.toLowerCase());

		return brewStrings.includes(testString);
	});
	return _.orderBy(brews, (brew)=>{ return this.sortBrewOrder(brew); }, this.state.sortDir);
},

toggleBrewCollectionState : function(brewGroupClass) {
	this.setState((prevState)=>({
fork icon293
star icon852
watch icon36

+ 9 other calls in file

115
116
117
118
119
120
121
122
123
124
125
  const sortAlbumsBy = getItemOrLast(options.sortAlbumsBy, this.depth)
  const sortAlbumsDirection = getItemOrLast(options.sortAlbumsDirection, this.depth)
  const sortMediaBy = getItemOrLast(options.sortMediaBy, this.depth)
  const sortMediaDirection = getItemOrLast(options.sortMediaDirection, this.depth)
  this.files = _.orderBy(this.files, SORT_MEDIA_BY[sortMediaBy], sortMediaDirection)
  this.albums = _.orderBy(this.albums, SORT_ALBUMS_BY[sortAlbumsBy], sortAlbumsDirection)
}


Album.prototype.pickPreviews = function (options) {
  // consider nested albums if there aren't enough photos
fork icon80
star icon649
watch icon20

+ 9 other calls in file

How does lodash.orderBy work?

lodash.orderBy works by taking three arguments: an array of objects to be sorted, a list of property names to be sorted by, and a list of sort directions for each property. The function first checks if any properties have a descending sort order and reverses the order of the array if necessary. It then sorts the array based on the first property in the list using the specified sort order. If two objects have the same value for the first property, lodash.orderBy then sorts them based on the second property, and so on for each subsequent property in the list. If any property has a missing or undefined value, lodash.orderBy treats it as a lower value than any defined value. Finally, the sorted array is returned as the result of the lodash.orderBy function. Note that lodash.orderBy can also sort properties in nested objects, and can use custom comparator functions to sort complex data types.

202
203
204
205
206
207
208
209
210
211
    roomId.push(item);
  }
}

const newData = JSON.stringify({
  roomId: _.orderBy(roomId, ['id'], ['asc']),
  buildTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
}, null, 2);

await fsP.writeFile(fileName, newData);
fork icon48
star icon185
watch icon11

25
26
27
28
29
30
31
32
33
34
35
36
}


async function findByRecordIds(frameworkIds) {
  const frameworkDatas = await frameworkDatasource.findByRecordIds(frameworkIds);
  const frameworks = _.map(frameworkDatas, (frameworkData) => _toDomain(frameworkData));
  return _.orderBy(frameworks, (framework) => framework.name.toLowerCase());
}


module.exports = {
  list,
fork icon47
star icon188
watch icon19

Ai Example

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

const users = [
  { name: "John", age: 30 },
  { name: "Jane", age: 25 },
  { name: "Bob", age: 35 },
];

const sortedUsers = _.orderBy(users, ["name", "age"], ["asc", "desc"]);

console.log(sortedUsers);

In this example, we first import the lodash library and define an array of objects representing users, with properties for their names and ages. We then use _.orderBy to sort the array by first sorting by the name property in ascending order, and then by the age property in descending order. The resulting sortedUsers array is [ { name: 'Bob', age: 35 }, { name: 'Jane', age: 25 }, { name: 'John', age: 30 } ], which is sorted first by name and then by age. Note that lodash.orderBy can also sort by nested properties, use custom comparator functions, and handle different data types, making it a versatile sorting function for complex data structures.

283
284
285
286
287
288
289
290
291
292
module.exports.nths                = _.nths;
module.exports.omit                = _.omit;
module.exports.omitBy              = _.omitBy;
module.exports.omitWhen            = _.omitWhen;
module.exports.once                = _.once;
module.exports.orderBy             = _.orderBy;
module.exports.over                = _.over;
module.exports.overArgs            = _.overArgs;
module.exports.overEvery           = _.overEvery;
module.exports.overSome            = _.overSome;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

504
505
506
507
508
509
510
511
512
513
      R.descend((obj) => obj.kConstant),
      R.ascend((obj) => obj.k1),
    ]
    return {
      iiris: () => A.sortWith(iirisComparators, shuffled),
      lodash: () => _.orderBy(shuffled, lodashIteratees, lodashOrders),
      ramda: () => R.sortWith(ramdaComparators, shuffled),
    }
  },
},
fork icon1
star icon31
watch icon0

131
132
133
134
135
136
137
138
139
140
  });
  return fieldTopicIdArray.join(' ');
};

liquid.filters.alphabetizeList = items => {
  return _.orderBy(items, [item => item?.name?.toLowerCase()], ['asc']);
};

liquid.filters.drupalToVaPath = content => {
  let replaced = content;
fork icon7
star icon15
watch icon0

602
603
604
605
606
607
608
609
610
611
  candidates.push(utils.getRandomElement(res.candidates));
  res.appropriate && res.candidates.length < coef && freeMasters.push(res);
}

if(freeMasters.length > coef) {
  freeMasters = _.orderBy(freeMasters, ['size', 'address'], ['desc', 'asc']); 
  freeMasters = freeMasters.slice(0, coef);
}

freeMasters = freeMasters.filter(m => m.address != this.address);
fork icon4
star icon14
watch icon4

+ 41 other calls in file

262
263
264
265
266
267
268
269
270
271
if (!mainStudyRightEducation) {
  return res
}

const snapshotStudyRightElements = []
const orderedSnapshots = orderBy(
  snapshots,
  [s => new Date(s.snapshot_date_time), s => Number(s.modification_ordinal)],
  ['desc', 'desc']
)
fork icon3
star icon12
watch icon0

674
675
676
677
678
679
680
681
682
683
  getFieldsToDisplay(obj.fields, locale, fields, obj.author_permlink, !!ownership.length));
/** Get right count of photos in object in request for only one object */
if (!fields) {
  obj.albums_count = _.get(obj, FIELDS_NAMES.GALLERY_ALBUM, []).length;
  obj.photos_count = _.get(obj, FIELDS_NAMES.GALLERY_ITEM, []).length;
  obj.preview_gallery = _.orderBy(
    _.get(obj, FIELDS_NAMES.GALLERY_ITEM, []), ['weight'], ['desc'],
  );
  if (obj.avatar) {
    obj.preview_gallery.unshift({
fork icon0
star icon3
watch icon3

248
249
250
251
252
253
254
255
256
257
258
259
260
console.log(keyBy); // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }


const map = _.map([4, 8], n => n * n);
console.log(map); // => [16, 64]


const orderBy = _.orderBy(['a', 'b', 'c'], ['c', 'a'], ['desc', 'asc']);
console.log(orderBy); // => ['c', 'a', 'b']


const partition = _.partition([1, 2, 3], n => n % 2);
console.log(partition); // => [[1, 3], [2]]
fork icon0
star icon1
watch icon1

+ 15 other calls in file

137
138
139
140
141
142
143
144
145
146

switch (orderBy) {
  case 'asc': {
    if (activeCropDataCopy.length > 0) {
      // TODO: replace _ lowdash with array function will need to write a custom orderby function.
      const updatedCropData = _.orderBy(activeCropDataCopy, activeObjKeys, [
        'asc',
        'asc',
        'asc',
      ]);
fork icon1
star icon0
watch icon4

721
722
723
724
725
726
727
728
729
730
);
/** Get right count of photos in object in request for only one object */
if (!fields) {
  obj.albums_count = _.get(obj, FIELDS_NAMES.GALLERY_ALBUM, []).length;
  obj.photos_count = _.get(obj, FIELDS_NAMES.GALLERY_ITEM, []).length;
  obj.preview_gallery = _.orderBy(_.get(obj, FIELDS_NAMES.GALLERY_ITEM, []), ['weight'], ['desc']);
  if (obj.avatar) {
    obj.preview_gallery.unshift({
      body: obj.avatar,
      name: FIELDS_NAMES.AVATAR,
fork icon0
star icon3
watch icon3

+ 2 other calls in file

119
120
121
122
123
124
125
126
127
128
let remediations = await queries.loadDetails(req.user.tenant_org_id, req.user.username, rows);

if (column === 'name') {
    // TODO: remove null name support?
    // if sorting by name re-order as db does not order null names (Unnamed playbook) properly
    remediations = _.orderBy(remediations, [r => (r.name || '').toLowerCase()], [asc ? 'asc' : 'desc']);
}

await P.all([
    resolveResolutionsNeedReboot(...remediations),
fork icon17
star icon1
watch icon8

+ 9 other calls in file

162
163
164
165
166
167
168
169
170
171
172
function isPromotedProject(project) {
  return project.status === "promoted";
}


function getDailyHotProjects(projects) {
  return orderBy(projects, "trends.daily", "desc")
    .slice(0, 5)
    .map(project => `${project.name} (+${project.trends.daily})`);
}

fork icon3
star icon7
watch icon2

+ 2 other calls in file

512
513
514
515
516
517
518
519
520
521
        // console.log('Noooooooooooooooooooooooooooooooooooooooooooooooo', course.title, course.vimeoUrl);
        return null;
    }

    // console.log('progressive', url, progressive);
    let video = orderBy(progressive, ['width'], ['desc'])[0];
    // console.log('video', video);
    return video.url;
} catch (err) {
    console.log('error with findVideoUrl:', course.title, course.vimeoUrl, '-->err:', err);
fork icon0
star icon5
watch icon1

459
460
461
462
463
464
465
466
467
468
    if (nextPageToken) {
        messageListResource.next_page_token = nextPageToken;
    }

    if (paramsArray.length > 1) {
        messageListResource.messages = _.orderBy(messageListResource.messages, 'date', 'desc').slice(0, params.limit);
    }

    return callback(null, messageListResource);
});
fork icon2
star icon1
watch icon6

+ 2 other calls in file

84
85
86
87
88
89
90
91
92
93
  if (LanguageUtils.isInstanceOf(criteria, Criteria)) {
    rubric.criterias.push(criteria)
  }
}
// Order criterias by criteria id
rubric.criterias = _.orderBy(rubric.criterias, ['criteriaId'])
for (let i = 0; i < levelsAnnotations.length; i++) {
  let levelAnnotation = levelsAnnotations[i]
  // Get criteria corresponding to the level
  let levelConfig = jsYaml.load(levelAnnotation.text)
fork icon0
star icon1
watch icon0

388
389
390
391
392
393
394
395
396
397
unVisitedUniqueOrders = uniqueOrders.filter((order) => {
  return order.visited != 1;
});
if (user.no_gps == 1) {
  allOrders.map((order) => (order.sequence = order.order_id));
  allOrders = lodash.orderBy(allOrders, ["sequence"], ["asc"]);
}
res.status(200).send({
  status: langObj.success_status_text,
  statusCode: 200,
fork icon1
star icon0
watch icon1

746
747
748
749
750
751
752
753
754
755

async writeVideosIntoFile(file, logger, prefix, courses, filename) {
    if (!file) {
        logger.info(`${prefix} - Starting writing to a file ...`)
        //await fs.writeFile(`./json/${filename}`, JSON.stringify(courses, null, 2), 'utf8');
        courses = orderBy(courses, [o => Number(o.downPath.split('-')[0]), 'position'], ['asc', 'asc']);
        courses = uniqBy(courses, 'url');
        await fs.ensureDir(path.resolve(__dirname, '../json'))
        await fs.writeFile(path.resolve(__dirname, `../json/${filename}`), JSON.stringify(courses, null, 2), 'utf8')
        logger.info(`${prefix} - Ended writing to a file ...`)
fork icon0
star icon4
watch icon1

+ 5 other calls in file

Other functions in lodash

Sorted by popularity

function icon

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