Feb 21, 2016
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:
That’s it. These two additions now make it possible to leverage natural sort on an array of objects by property name.
If you have improvement ideas or any other thoughts, just reach out on Twitter @derekknox or email me derek [at] derekknox.com.