ArticleZip > Array With Object Sorting With Underscore Sortby

Array With Object Sorting With Underscore Sortby

Are you looking to master the art of sorting arrays with objects in your code using the powerful `_.sortBy` function in Underscore.js? Let's dive into this handy feature and explore how you can efficiently organize your data.

First things first, why would you even need to sort an array of objects? Imagine you have a plethora of data in the form of objects and want to rearrange them based on specific criteria like the object's properties. That's where `_.sortBy` from Underscore.js swoops in to save the day!

Now, let's break it down into simple steps. To begin with, you'll need to ensure you have Underscore.js included in your project. If you haven't already added it, you can easily do so by including it through a CDN or by installing it using a package manager like npm.

Once you've got Underscore.js all set up, it's time to create your array of objects that you want to sort. Let's say you have an array of objects representing different books with properties like `title`, `author`, and `publishedDate`.

To sort these objects by a specific property, all you need to do is pass in the array and a function that specifies the property by which you want to sort. Here's an example code snippet to illustrate this:

Javascript

const books = [
  { title: 'The Catcher in the Rye', author: 'J.D. Salinger', publishedDate: '1951' },
  { title: 'To Kill a Mockingbird', author: 'Harper Lee', publishedDate: '1960' },
  { title: '1984', author: 'George Orwell', publishedDate: '1949' }
];

const sortedBooks = _.sortBy(books, (book) => book.publishedDate);

In this case, we're sorting the `books` array based on the `publishedDate` property of each book object. You can replace `publishedDate` with any other property you wish to sort by.

Additionally, you can sort in ascending or descending order by simply adjusting the function inside `_.sortBy`. To sort in descending order, you can modify the function like this:

Javascript

const sortedBooksDesc = _.sortBy(books, (book) => -book.publishedDate);

And voila! You've successfully sorted your array of objects using Underscore.js's `_.sortBy` function.

One important thing to note is that `_.sortBy` does not modify the original array; instead, it returns a new sorted array. So make sure to capture the result in a new variable if you want to retain the original order for future use.

In conclusion, mastering the art of sorting arrays with objects using Underscore.js's `_.sortBy` function can greatly enhance the organization and efficiency of your code. With just a few lines of code, you can effortlessly sort your data based on specific criteria, making your code cleaner and more manageable.

×