Firstly, Date
objects can be compared directly.
Secondly, even if you did need to convert to something numeric, Date
already has a getTime
method, which returns an Epoch timestamp with milliseconds.
Thirdly, your function has serious side-effects. It overwrites a property on every object - which there's really no call for.
And lastly, you're missing semicolons, and should indent the chained function calls.
You should be able to get by with just:
var sorted = _.sortBy(arr, dateProp);
Or, without any libraries whatsoever:
function orderByDate(arr, dateProp) {
return arr.slice().sort(function (a, b) {
return a[dateProp] < b[dateProp] ? -1 : 1;
});
}
Of course, if your dates are strings, you may need moment.js for that (though JS's Date
can parse some stuff on its own). But in that case, you should probably also supply moment.js with the format it's supposed to parse, or at least have it as an optional argument.