How to sort alphabetically an array of objects by key in JavaScript
Sorting an array of objects in JavaScript can be a nightmare if you don't know about the right logic to do it. The preferred way to sort an array is using its sort method, a method that sorts the elements of an array in place. The default sort order is according to the string Unicode code points.
In this article, we'll share with you a very simple, functional and optimized method to sort an array of objects by some key in ascending or descending order using plain JavaScript (no extra frameworks).
1. Create/expose some data to sort
As first step, to sort an array of objects by some key, you will need a valid structure in your array, obviously an array of objects can only have objects with at least one key (the one that you want to sort). In this example, we'll have the MyData variable that has the following structure:
Every item has 3 keys that can be sorted as well numerically and alphabetically.
2. Create custom sort function
JavaScript offers a native method that expects as first argument a function to sort according to your needs, so is up to you to write that function. The point of this article is to show you how to sort by some key an array of objects, so we'll dispose this function for you that you can simply use:
As mentioned, this function needs to be injected as first argument to the prototype sort function of an array in JavaScript, so you won't use it directly as it will just return 0 or 1. The main point of this function to sort is the localeCompare, a function of JavaScript included in the prototype of strings that returns a number indicating whether the string1 comes before, after or is the same as string2 in sort order (values).
3. Sort by key in ascending order
Finally, to sort an array of objects, simply call the sort method of the array and pass as first argument the dynamicSort
function that expects as well as first argument a string, namely the key of the object that you want to sort. In this case, we could start by sorting by the name property using the following line of code:
Important
Note that the sort method reorders/sort the items of the array in the same variable (by reference), so the method doesn't return a new variable with the new order but the same variable will be modified in-place.
With the previous code, the console.log
would output the object with the new order:
Or try with a new key, for example city:
This would output instead:
4. Sort by key in descending order
To sort an array of objects by some key alphabetically in descending order, you only need to add as prefix a -
(minus) symbol at the beginning of the key string, so the sort function will sort in descending order:
This would output:
Happy coding !
Comments
Post a Comment