Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting of array with Moment(date) elements

I have an array that is populated with moment(Date provided by the database) elements. I am trying to sort the array so that the first element is the oldest and the last element is the newest, but with no success.

     for (let item of items) {

            dates.push(moment(item.created));
          }
          dates.sort(function(a,b){
            var da = new Date(a).getTime();
            var db = new Date(b).getTime();

            return da < db ? -1 : da > db ? 1 : 0
          });
    }
  console.log(dates);

This always prints the current time times number of elements.

like image 380
John V Avatar asked Nov 12 '18 14:11

John V


1 Answers

It's much easier than you think. :-) When you use - on a operands that are Moment instance, they're coerced to numbers, which are their milliseconds-since-the-Epoch value. So:

dates.sort((a, b) => a - b);

...sorts them ascending (earliest dates first), and

dates.sort((a, b) => b - a);

...sorts them descending (latest dates first).

I've happily used concise arrow functions there, since you're already using ES2015+ features in your code.

Example:

let dates = [
  moment("2017-01-12"),
  moment("2018-01-12"),
  moment("2017-07-12"),
  moment("2016-07-30")
];
dates.sort((a, b) => a - b);
console.log(dates);

dates = [
  moment("2017-01-12"),
  moment("2018-01-12"),
  moment("2017-07-12"),
  moment("2016-07-30")
];
dates.sort((a, b) => b - a);
console.log(dates);
.as-console-wrapper {
  max-height: 100% !important;
}
The built-in Stack Snippets console shows Moment instances by calling toString, which shows is the ISO date string. But they're Moment instances (you can see that in the browser's real console).
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
like image 186
T.J. Crowder Avatar answered Nov 15 '22 18:11

T.J. Crowder