This post will discuss how to sort an array of objects in JavaScript.

1. Using Array.sort() method

JavaScript native method sort() is commonly used to in-place sort elements of an array. The sort() method optionally accepts a comparison function, which defines the sort order. If x and y are two elements being compared with comparison function comp, then if :

  • comp(x, y) < 0, x comes before y in sorted order.
  • comp(x, y) = 0, the relative order of x and y remains unchanged.
  • comp(x, y) > 0, x comes after y in sorted order.

 
You can implement the comparison function with either function expressions or arrow functions. Without the comparison function, all elements will be converted to the string, and the comparison is made using the lexicographic order. Any undefined elements are moved at the end of the array.

 
The sort() method can be used to sort an array of objects using one or more of their properties. The following code example demonstrates the usage of the sort() method to sort an array of objects using the year field.

Download  Run Code

 
For comparing strings, you can use the String.localeCompare() method.

Download  Run Code

 
The String.localeCompare() is case-insensitive. For case-sensitive comparison, you can use the following code:

 
To sort by multiple fields, you can do like:

2. Using _.sortBy() method

If you’re already using lodash or underscore JavaScript library, you can use the _.sortBy method. It sorts the array in ascending order with one or more fields. The following example demonstrates the usage of the _.sortBy by sorting the array first by the year field, followed by the name field.

Download Code

 
The _.sortBy method does not allow to sort the array in descending order, but you can call the reverse() method after a sort to reverse the order.

Download Code

3. Using _.orderBy() method

Alternatively, you can use the _.orderBy method (offered by Lodash only), which optionally allows you to specify the sort order. The following example demonstrates this by sorting the array first by the name field in ascending order and then by the year field in descending order.

Download Code

That’s all about sorting an array of objects in JavaScript.