Moment JS

Example of parsing and formatting a Date with Moment JS.

by Korah Babu Varghese

HTML

<script src="http://momentjs.com/downloads/moment.js"></script>

JavaScript

var data = {'August.2018': {Flights: 274834},
'December.2019': {Flights: 222036},
'February.2019': {Flights: 299376},
'January.2019': {Flights: 399559},
'July.2019': {Flights: 187985},
'June.2019': {Flights: 143985},
'March.2019': {Flights: 242277},
'November.2019': {Flights: 194460},
'October.2019': {Flights: 1943880},
'September.2019': {Flights: 122304}};
// object which holds the order value of the month
var monthNames = [
  "January",
  "February",
  "March",
  "April",
  "May",
  "June",
  "July",
  "August",
  "September",
  "October",
  "November",
  "December"
];

// sort the data array
Object.keys(data).sort(function(a, b) {
  // sort based on the value in the monthNames object
  return monthNames[moment(a[0],'MMMM').format('MMMM')] - monthNames[moment(B[0],'MMMM').format('MMMM')];
});

document.write('<pre>' + JSON.stringify(data, 0, 3) + '</pre>')