Order array of objects by date property 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()
}
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] &lt; 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.