ArticleZip > How Can I Use Lodash Underscore To Sort By Multiple Nested Fields

How Can I Use Lodash Underscore To Sort By Multiple Nested Fields

Sorting data in JavaScript can sometimes get tricky, especially when you need to sort by multiple nested fields. But fear not, for tools like Lodash and Underscore can come to the rescue, making the task a breeze.

First things first, make sure you have Lodash or Underscore included in your project. If you don't already have them, you can easily add them using npm or yarn:

Bash

npm install lodash
# or
yarn add lodash

Once you have Lodash in your project, sorting by multiple nested fields becomes a straightforward task. Let's dive into the code:

Javascript

const data = [
  { name: 'Alice', details: { age: 25, city: 'New York' } },
  { name: 'Bob', details: { age: 30, city: 'San Francisco' } },
  { name: 'Charlie', details: { age: 22, city: 'Los Angeles' } },
];

const sortedData = _.orderBy(data, ['details.city', 'details.age'], ['asc', 'desc']);
console.log(sortedData);

In this example, we have an array of objects with nested details. To sort this array by the city in ascending order and age in descending order, we use the `orderBy` function from Lodash. The first argument is the array we want to sort, the second argument is an array of keys to sort by, and the third argument is an array of sorting orders for each key.

If you want to sort in descending order for both fields, you can simply adjust the sorting orders like this:

Javascript

const sortedData = _.orderBy(data, ['details.city', 'details.age'], ['desc', 'desc']);

And that's it! With just a few lines of code using Lodash or Underscore, you can easily sort your data by multiple nested fields without breaking a sweat.

In conclusion, when it comes to sorting data by multiple nested fields in JavaScript, Lodash and Underscore provide handy functions like `orderBy` to simplify the process. By leveraging these tools, you can efficiently organize your data according to your specific sorting criteria. So next time you encounter the need to sort complex data structures, remember to turn to Lodash or Underscore for help!