four-eyes
four-eyes

Reputation: 12439

Sort by Date ImmutableJS and Moment()

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

Answers (2)

Eugene Tsakh
Eugene Tsakh

Reputation: 2879

Try this:

arrayOfObjects.sort((a, b) => b.get('date').unix() - a.get('date').unix());

Upvotes: 0

Akrion
Akrion

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

Related Questions