Natural Sort in Angular JS
The purpose of this article is to showcase the Angular JS natural sort solution of Ben Nadel and Phil DeJarnett. In addition, I propose an improvement that accounts for using natural sort against an array of objects by property name.
In a recent project, I needed to improve the alphanumeric sorting of a product list as it didn’t sort the numbered products as one would expect. For example the sort would result in:
When the expectation is:
Phil’s solution is excellent, but it fell slightly short for me. The issue I ran into after implementing Phil’s solution was that it didn’t allow for the sorting of an array of objects by property name. It assumed the array to sort was a list of strings.
Through digging into the source code, I was able to quickly determine what changes were needed. The edits I made are small and quite simple too. In fact there are only two core changes:
- I wrap the natural sort function in another function adding the ability to pass an optional argument while ensuring the original sort function returns.
- I use bracket notation in combination with the ternary operator to succinctly update the sort using the aforementioned property name argument if it exists. Otherwise the sort occurs as originally designed.
That’s it. These two additions now make it possible to leverage natural sort on an array of objects by property name.
Before - naturalSortVersionDatesCaching.js
If you have improvement ideas or any other thoughts, just reach out on Twitter @derekknox or email me derek [at] derekknox.com.