6

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?

Newtt
  • 5,331
  • 12
  • 58
  • 95
  • Here's the answer http://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order – mguimard Sep 04 '15 at 07:20
  • @mguimard But the use of `const` would indicate [ES6](http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties), not ES5 – CodingIntrigue Sep 04 '15 at 07:24

4 Answers4

10

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>
CodingIntrigue
  • 65,670
  • 26
  • 159
  • 166
2
Without moment library you can also do. It will work for all js framework

var testObj = {
  "3/10/2015": {},
  "2/10/2015": {},
  "1/10/2015": {},
  "4/10/2015": {},
  "29/09/2015": {},
  "30/09/2015": {}
};
var ordered = {};
Object.keys(testObj).sort(function(a, b) {
  return (dateConverter(a) - dateConverter(b));
}).forEach(function(key) {
  ordered[key] = testObj[key];
});

/* Convert DD/MM/YY to date object */
function dateConverter(date) {
  var dateParts = date.split("/");
  var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]); 
  return dateObject
}
/* ordered return now                                               
  "1/10/2015": {},
  "2/10/2015": {},
  "3/10/2015": {},
  "4/10/2015": {},
  "29/09/2015": {},
  "30/09/2015": {} */
Gautam
  • 1,442
  • 15
  • 16
  • for me ordered object was still not ordered after the forEach loop. Within the loop, however, the elements were in order. I guess it is because you are assigning testObj to a dictionary, which does not guarantee order – Boris Mocialov Jul 26 '19 at 11:38
2

Without moment, easier sorting can be achieved if the date is in the format 'YYYYMMDD' with any separator.

const testObj = {
  "1/10/2015": {},
  "2/10/2015": {},
  "3/10/2015": {},
  "4/10/2015": {},
  "29/09/2015": {},
  "30/09/2015": {}
};

const orderedDates = {};
Object.keys(testObj).sort(function(a, b) {
  return a.split('/').reverse().join('').localeCompare(b.split('/').reverse().join(''));
}).forEach(function(key) {
  orderedDates[key] = testObj[key];
})

console.log(orderedDates);
Jonas Tomanga
  • 880
  • 9
  • 15
0

Using the moment package, you can use:

const yourFormat = 'DD/MM/YYYY'
const sortDateMoments = (dates) => {
  const moments = dates.map(date => moment(date, yourFormat))
  moments.sort((a, b) => a.isBefore(b) ? 1 : -1)
  return moments
}
shapiro yaacov
  • 2,173
  • 2
  • 24
  • 34