I have the following object structure
{ "Apr-18" : { ... },
"Jan-18" : { ... },
"Feb-18" : { ... },
...
}
I am trying to sort the month (MMM-YY) keys so that it shows as follows
{ "Jan-18" : { ... },
"Feb-18" : { ... },
"Apr-18" : { ... },
...
}
My code for this is below. I am using moment.js to convert the date into its epoch for the sort comparison. I have roughly followed the solution shown here Sort JavaScript object by key However it's not working.
The console.log returns the object as it was, no sorting has occurred. What am I missing?
const object = {
"Apr-18" : { "a":"b" },
"Jan-18" : { "c":"d" },
"Feb-18" : { "e":"f" }
}
const sortObjectMonths = (obj) => Object.fromEntries(Object.entries(obj).sort( (a, b) =>
Date.parse(moment(a, "MMM-YY") - Date.parse(moment(b, "MMM-YY")))
));
let sorted = sortObjectMonths(object)
console.log(sorted)