I have a JavaScript object that looks like follows
testObj = {
1/10/2015: {},
2/10/2015: {},
3/10/2015: {},
4/10/2015: {},
29/09/2015: {},
30/09/2015: {}
}
Now, I'm trying to sort this such that the dates are arranged by date in increasing order. For that i've done the following
const orderedDates = {};
Object.keys(testObj).sort(function(a, b) {
return moment(moment(b, 'DD/MM/YYYY') - moment(a, 'DD/MM/YYYY')).format('DD/MM/YYYY');
}).forEach(function(key) {
orderedDates[key] = testObj[key];
})
rangeObj = orderedDates;
This however is not sorting the dates at all. It still returns the same exact object as testObj
. How do I sort the object based on date keys?
To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.
To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
Arrays of objects can be sorted by comparing the value of one of their properties.
This line returns a string:
moment(moment(b, 'DD/MM/YYYY') - moment(a, 'DD/MM/YYYY')).format('DD/MM/YYYY')
But the sort method requires an integer value, so you need to compare the actual dates instead:
Object.keys(testObj).sort(function(a, b) {
return moment(b, 'DD/MM/YYYY').toDate() - moment(a, 'DD/MM/YYYY').toDate();
}).forEach(function(key) {
orderedDates[key] = testObj[key];
})
However you need to be aware that in ES5, the order of keys in an object was not guaranteed by the spec - although most browsers did iterate the keys in insertion order. In ES6 however, you can be guaranteed that if you iterate your objects keys they will be in order.
So console.log(orderedDates)
may not show the keys in your expected order, but Object.keys(orderedDates).forEach(function(date) { console.log(date); });
will work as expected.
var testObj = {
"1/10/2015": {},
"2/10/2015": {},
"3/10/2015": {},
"4/10/2015": {},
"29/09/2015": {},
"30/09/2015": {}
};
var orderedDates = {};
Object.keys(testObj).sort(function(a, b) {
return moment(b, 'DD/MM/YYYY').toDate() - moment(a, 'DD/MM/YYYY').toDate();
}).forEach(function(key) {
orderedDates[key] = testObj[key];
})
Object.keys(orderedDates).forEach(function(date) {
document.body.innerHTML += date + "<br />"
});
<script src="http://momentjs.com/downloads/moment.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With