var sorted = results.sort(function (a, b) {
var nameA = "";
var nameB = "";
var str1 = a.date.toLowerCase() + " " + a.time;
var str2 = b.date.toLowerCase() + " " + b.time;
if (a.date.toLowerCase() != "" && a.time!= "")
nameA = Date.parse(new Date(str1))
if (b.date.toLowerCase() != "" && b.time!= "")
nameB = Date.parse(new Date(str2))
return nameA === nameB ? 0 : nameA < nameB ? -1 : 1;
});
- Can anyone improve the code, if there any faults in the way i am
sorting. Is there any better approach? - How can i implement
http://underscorejs.org/#sortByfor the above
sorting.
One major bottleneck in your code is that you’re recomputing nameA/nameB on every sort operation. Considering that each element in array may take part in several comparisons, that’s a lot of unnecessary work. You should first build sorting index using same algorithm and then sort with it instead. You can also store sort key in same object you sort so you can just check if it is here and don’t recompute it if it is.
Another two things in your code are absolutely unnecessary:
.toLowerCaseon comparison with empty string and generation of uselessDataobjects, whenData.parsealready specified explicitly as working with strings.I’ve made two versions of improved sort – one with helper function (prettier, more correct ideologically) and inline – may give some extra speed-up on some JS engines. They both run roughly 3000 times faster than your original: http://jsperf.com/custom-date-sort.
(Oh, and helper function happens to be suitable for your underscore sortBy question).
With helper:
Inline: