Search code examples
javascriptsortingmomentjslodash

lodash - order dates with skipping year value


var dates = ['2017-02-01', '2017-01-01', '2016-02-03', '2018-02-02', '2014-12-25'];
var orderedDates = dates.sort(); // ['2017-01-01', '2017-02-01', '2018-02-02', '2016-02-03', '2014-12-25']

I have collection of dates(moment objects) from different year. I need to sort this dates only by 'ddMM' format (like skip years).

Is there any way to do this?

create copy of dates array, set same year for all dates - not seem like good solution.

for sorting use lodash .orderBy


Solution

  • You should use the 'MMDD' format and not 'DDMM'.

    And it is not necessary to convert it back to a moment, since it is just to sort the array.

    var orderedDates = _.orderBy(dates, e => moment(e).format('MMDD'));