Reputation: 12439
I have an array
of objects
. The objects have the key date
. The date
is a moment
formatted date
, created like this: moment('1970-11-11')
.
How do I sort the array by date in ascending/descending order?
That
arrayOfObjects.sort((a, b) => b.get('date') - a.get('date');
nor
arrayOfObjects.sort((a, b) => b.get('date').format('DD.MM.YYYY') - a.get('date').format('DD.MM.YYYY'))
does not sort it.
Upvotes: 0
Views: 277
Reputation: 2879
Try this:
arrayOfObjects.sort((a, b) => b.get('date').unix() - a.get('date').unix());
Upvotes: 0
Reputation: 18525
Pardon me for asking but if I understand correctly you have moment
objects in that array fully capable of doing date calculations and difference. So if that is the case why not:
var data = [moment('1972-11-11'), moment('1971-11-11'), moment('1973-11-11')]
const result = data.sort((a,b) => a.diff(b)) // change to b.diff(a) for desc
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
As per moment documentation on diff
. No need to date/unix
etc.
Upvotes: 1