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)
Your code is almost okay but in .sort() the element a and b both are arrays of key and value. Key is at index 0 and value at index 1. Date.parse() won't work and converting the value by using new Date() is suggested. So, your code should be -
const moment = require("moment");
const sort = {
clientname: {
"Feb-18": { test: "c" },
"Jan-18": { test: "a" },
"Apr-18": { test: "v" },
},
};
const sortObjectMonths = (obj) => {
return Object.fromEntries(
Object.entries(obj).sort(
(a, b) => moment(new Date(a[0])) - moment(new Date(b[0]))
)
);
};
let sorted = sortObjectMonths(sort.clientname);
console.log(sorted);
You can use Object.entries() to get the object property keys and values, then use Array.sort() to sort them using moment. We can simply subtract the moment values to sort them.
The Array.sort() accepts two arguments, firstEl, secondEl, in this case that will be [key1, value1], [key2, value2]. We can use destructuring to write these as ([a,],[b,]), where a and b are the object keys (e.g. 'Apr-18').
Then we'll use Object.fromEntries() to get our sorted object.
const object = {
"Apr-18" : { "a":"b" },
"Jan-18" : { "c":"d" },
"Feb-18" : { "e":"f" },
}
console.log('Original object:', object)
const sortedObject = Object.fromEntries(
Object.entries(object).sort(([a,],[b,]) => {
return moment(a, "MMM-YY") - moment(b, "MMM-YY");
})
)
console.log('Sorted object:', sortedObject)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>
Without moment
const months = ["Jan","Feb","Mar","Apr"]
const object = {
"Apr-18" : { "a":"b" },
"Jan-18" : { "c":"d" },
"Feb-18" : { "e":"f" },
}
const sortedObject = Object.fromEntries(
Object.entries(object)
.sort(([a,],[b,]) => months.indexOf(a.split("-")[0]) - months.indexOf(b.split("-")[0]))
)
console.log('Sorted object:', sortedObject)