Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Sorting by a Single Property:
4.2.
JavaScript
4.3.
Sorting by Multiple Criteria:
4.4.
JavaScript
4.5.
Sorting Using a Custom Function:
4.6.
JavaScript
4.7.
Complex Sorting of Nested Objects:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
How does _.orderBy() handle null and undefined values?
5.2.
Can _.orderBy() be used with different types of collections?
5.3.
Is _.orderBy() efficient for large datasets?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.orderBy() Method

Author Riya Singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Sorting collections based on multiple criteria is a common yet complex task in JavaScript programming. Lodash simplifies this with the _.orderBy() method. This versatile function sorts a collection of elements based on specified iteratee functions and their corresponding sort orders. 

Lodash _.orderBy() Method

This article will provide a comprehensive understanding of the _.orderBy() method, its syntax, usage, and practical applications, supported by illustrative examples and FAQs.

Why This Function is Used

The _.orderBy() function is used to sort a collection (such as an array of objects) based on one or more criteria. This is particularly useful in scenarios like data reporting, user interfaces displaying sorted data, or any situation requiring a custom sort order. The method excels in its ability to handle complex sorting requirements, including sorting by multiple fields, each with its own ascending or descending order.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.orderBy(collection, [iteratees=[_.identity]], [orders])

Parameters:

  • collection (Array|Object): The collection to iterate over.
     
  • [iteratees=[_.identity]] (Array[]|Function[]|Object[]|string[]): The iteratees to sort by.
     
  • [orders] (string[]): The sort orders of iteratees.

Return Value: 

(Array) - Returns the new sorted array.

Examples 

Sorting by a Single Property:

  • JavaScript

JavaScript

var _ = require('lodash');

var users = [{ 'user': 'fred', 'age': 48 },

            { 'user': 'barney', 'age': 36 },

            { 'user': 'fred', 'age': 40 }];

var orderedByAge = _.orderBy(users, ['age'], ['asc']);

console.log(orderedByAge);

 Output: 

[{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }, { 'user': 'fred', 'age': 48 }]


Demonstrates sorting an array of objects by the age property in ascending order.

Sorting by Multiple Criteria:

  • JavaScript

JavaScript

var orderedByNameThenAge = _.orderBy(users, ['user', 'age'], ['asc', 'desc']);

console.log(orderedByNameThenAge);

Output: 

[{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 48 }, { 'user': 'fred', 'age': 40 }]


Shows sorting first by user in ascending order, then by age in descending order.

Sorting Using a Custom Function:

  • JavaScript

JavaScript

var items = [1.1, 2.3, 1.4];

var orderedByFloorValue = _.orderBy(items, [Math.floor], ['asc']);

console.log(orderedByFloorValue);

Output:

[1.1, 1.4, 2.3]


An example of sorting numbers by their integer part in ascending order.

Complex Sorting of Nested Objects:

  • JavaScript

JavaScript

var products = [{ 'details': { 'name': 'apple', 'weight': 0.5 }}, 

               { 'details': { 'name': 'pear', 'weight': 0.3 }}];

var orderedByWeight = _.orderBy(products, ['details.weight'], ['desc']);

console.log(orderedByWeight);

Output: 

[{ 'details': { 'name': 'apple', 'weight': 0.5 }}, { 'details': { 'name': 'pear', 'weight': 0.3 }}]


Demonstrates sorting an array of objects with nested properties.

Frequently Asked Questions 

How does _.orderBy() handle null and undefined values?

_.orderBy() will sort null and undefined values based on JavaScript's < and > comparison rules, typically placing them at the end in ascending order.

Can _.orderBy() be used with different types of collections?

Yes, it can sort arrays and array-like objects, but the most common use case is sorting arrays of objects based on specific properties.

Is _.orderBy() efficient for large datasets?

While _.orderBy() is generally efficient, its performance may vary based on the complexity of the iteratees and the size of the dataset.

Conclusion

Lodash's _.orderBy() method is a flexible and powerful tool for sorting collections based on multiple criteria. It offers an intuitive and customizable approach to ordering elements, catering to complex sorting needs in JavaScript.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.differenceWith() Method
Next article
Lodash _.flattenDeep() Method
Live masterclass