6
\$\begingroup\$

Here's a function that sorts an array of objects with a dateProp by the date. First it uses moment to convert the Date object to a unix timestamp.

var _ = require('lodash')
var moment = require('moment')

util.orderByDate = function (arr, dateProp) {
  if (!dateProp) return arr
  return _.chain(arr)
  .map(function (item) {
    item[dateProp] = moment(item[dateProp]).format('x')
    return item
  })
  .sortBy(dateProp)
  .value()
}
\$\endgroup\$
7
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ If you just do [array of dates].sort(), they will be sorted from the latest date to the earliest date. \$\endgroup\$ – SirPython Sep 8 '15 at 22:21
  • 1
    \$\begingroup\$ @SirPython True, but the input isn't an array of dates, but an array of objects that contain dates. As far as I can tell, that's what OP wants to sort, though the code does something else entirely \$\endgroup\$ – Flambino Sep 8 '15 at 22:23
  • \$\begingroup\$ @SirPython Oops, I was partly mistaken. It's not that OP's code does "something else entirely" (I misread the map call). It does however have some nasty side-effects \$\endgroup\$ – Flambino Sep 8 '15 at 22:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.