Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.sortBy() Collection Method

Posted in lodash Tutorial
Updated on Nov 22, 2024
By Mari Selvan
👁️ 43 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.sortBy() Collection Method

Photo Credit to CodeToFun

🙋 Introduction

In the vast landscape of JavaScript development, effective manipulation and sorting of collections are common tasks. Lodash, a feature-rich utility library, provides a wealth of functions to streamline these operations. Among them, the _.sortBy() method stands out as a versatile tool for sorting collections based on specified criteria.

Whether you're dealing with arrays of objects or other complex data structures, _.sortBy() simplifies the process of arranging elements in a meaningful order.

🧠 Understanding _.sortBy() Method

The _.sortBy() method in Lodash facilitates the sorting of a collection based on the values computed from each element. It allows developers to define custom sorting criteria through an iteratee function, providing flexibility in arranging data as per their requirements.

💡 Syntax

The syntax for the _.sortBy() method is straightforward:

syntax.js
Copied
Copy To Clipboard
_.sortBy(collection, [iteratees])
  • collection: The collection to iterate over.
  • iteratees (Optional): The iteratee functions, invoked per iteration.

📝 Example

Let's dive into a simple example to illustrate the usage of the _.sortBy() method:

example.js
Copied
Copy To Clipboard
const _ = require('lodash');

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

const sortedUsers = _.sortBy(users, ['age']);

console.log(sortedUsers);
/*
Output:
[
    { name: 'Alice', age: 25 },
    { name: 'John', age: 30 },
    { name: 'Bob', age: 35 }
]
*/

In this example, the users array is sorted based on the 'age' property using _.sortBy().

🏆 Best Practices

When working with the _.sortBy() method, consider the following best practices:

  1. Understand Iteration Order:

    Be aware of the iteration order when using _.sortBy(). The method relies on the built-in Array#sort() method, which may not guarantee a stable sort. If a stable sort is essential, consider using _.orderBy().

    example.js
    Copied
    Copy To Clipboard
    const unorderedData = [
        { id: 1, value: 'apple' },
        { id: 2, value: 'banana' },
        { id: 3, value: 'orange' },
        { id: 4, value: 'apple' },
    ];
    
    const sortedData = _.sortBy(unorderedData, ['value']);
    console.log(sortedData);
    /*
    Potential Output:
    [
        { id: 1, value: 'apple' },
        { id: 4, value: 'apple' },
        { id: 2, value: 'banana' },
        { id: 3, value: 'orange' }
    ]
    */
  2. Multiple Criteria Sorting:

    Leverage the ability to sort by multiple criteria by passing an array of properties or iteratee functions to _.sortBy().

    example.js
    Copied
    Copy To Clipboard
    const complexData = [
        { name: 'John', age: 30, score: 85 },
        { name: 'Alice', age: 25, score: 95 },
        { name: 'Bob', age: 35, score: 90 },
    ];
    
    const multiSortedData = _.sortBy(complexData, ['age', 'score']);
    console.log(multiSortedData);
    /*
    Output:
    [
        { name: 'Alice', age: 25, score: 95 },
        { name: 'John', age: 30, score: 85 },
        { name: 'Bob', age: 35, score: 90 }
    ]
    */
  3. Custom Iteratee Functions:

    For advanced sorting logic, create custom iteratee functions to extract values or perform computations on elements.

    example.js
    Copied
    Copy To Clipboard
    const customSortedData = _.sortBy(users, user => user.name.length);
    console.log(customSortedData);
    /*
    Output:
    [
        { name: 'Bob', age: 35 },
        { name: 'John', age: 30 },
        { name: 'Alice', age: 25 }
    ]
    */

📚 Use Cases

  1. Sorting Objects by Property:

    _.sortBy() is excellent for sorting an array of objects based on a specific property, providing a quick and efficient way to organize data.

    example.js
    Copied
    Copy To Clipboard
    const products = [
        { name: 'Laptop', price: 800 },
        { name: 'Smartphone', price: 500 },
        { name: 'Tablet', price: 300 },
    ];
    
    const sortedProducts = _.sortBy(products, ['price']);
    console.log(sortedProducts);
    /*
    Output:
    [
        { name: 'Tablet', price: 300 },
        { name: 'Smartphone', price: 500 },
        { name: 'Laptop', price: 800 }
    ]
    */
  2. Sorting Strings:

    Sorting an array of strings alphabetically or based on custom criteria becomes straightforward with _.sortBy().

    example.js
    Copied
    Copy To Clipboard
    const words = ['banana', 'apple', 'orange', 'grape'];
    
    const sortedWords = _.sortBy(words);
    console.log(sortedWords);
    // Output: ['apple', 'banana', 'grape', 'orange']
  3. Numeric Sorting:

    Numeric sorting of arrays containing numbers can be efficiently accomplished using _.sortBy().

    example.js
    Copied
    Copy To Clipboard
    const numbers = [10, 5, 20, 15];
    
    const sortedNumbers = _.sortBy(numbers);
    console.log(sortedNumbers);
    // Output: [5, 10, 15, 20]

🎉 Conclusion

The _.sortBy() method in Lodash is a valuable tool for sorting collections in JavaScript, offering flexibility and efficiency. Whether you're working with arrays of objects, strings, or numbers, this method simplifies the sorting process and allows for customization based on specific criteria.

By adhering to best practices and exploring diverse use cases, you can harness the full potential of the _.sortBy() method in your Lodash projects.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy