Moment: Sort Comparison Function

Created on 25 Feb 2014  ·  6Comments  ·  Source: moment/moment

When sorting a list of moment objects (or objects that have an attribute that is a moment, and should be the sort key), it would be great if there was a comparison function included. So that we could do things like:

array.sort(m.compare)

Most helpful comment

Because of the moment#valueOf function, the compare function is trivial.

var array = [
    moment(),
    moment().add(1, 'd'),
    moment().subtract(1, 'd')
];

console.log(array.map(function (m) {
    return m.format('YYYY-MM-DD')
}));
// ["2014-02-24", "2014-02-25", "2014-02-23"] 

array.sort(function (a, b) {
    return a - b;
});

console.log(array.map(function (m) {
    return m.format('YYYY-MM-DD')
}));
// ["2014-02-23", "2014-02-24", "2014-02-25"]

All 6 comments

Because of the moment#valueOf function, the compare function is trivial.

var array = [
    moment(),
    moment().add(1, 'd'),
    moment().subtract(1, 'd')
];

console.log(array.map(function (m) {
    return m.format('YYYY-MM-DD')
}));
// ["2014-02-24", "2014-02-25", "2014-02-23"] 

array.sort(function (a, b) {
    return a - b;
});

console.log(array.map(function (m) {
    return m.format('YYYY-MM-DD')
}));
// ["2014-02-23", "2014-02-24", "2014-02-25"]

Thanks.

I was explicitly using moment#valueOf, this looks like I don’t need to.

With typescript, this is not as simple. The typings don't allow you to say a - b.

Instead, I just say something like:

a.isBefore(b) ? -1 : 1

Not sure if I got that 1 and -1 the right way around.

With typescript, this is not as simple. The typings don't allow you to say a - b.

You can explicitly call the moment#valueOf as a.valueOf() - b.valueOf()

I'm partial to:

momentsArray.sort((a, b) => a.diff(b));

myself.

@robertmassaioli be careful with your code,

a.isBefore(b) ? -1 : 1

if a is the same, it would swap them, rather than keep them in place. I know it doesn't sound like much but it could be unexpected for some.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nikocraft picture nikocraft  ·  3Comments

ninigix picture ninigix  ·  3Comments

RobinvanderVliet picture RobinvanderVliet  ·  3Comments

IbraheemAlSaady picture IbraheemAlSaady  ·  3Comments

BCup picture BCup  ·  3Comments