Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort Comparison Function #1493

Closed
schinckel opened this issue Feb 24, 2014 · 6 comments
Closed

Sort Comparison Function #1493

schinckel opened this issue Feb 24, 2014 · 6 comments

Comments

@schinckel
Copy link

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)
@timrwood
Copy link
Member

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"]

@schinckel
Copy link
Author

Thanks.

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

@robertmassaioli
Copy link

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.

@libinvarghese
Copy link

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()

@saveriodesign
Copy link

I'm partial to:

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

myself.

@WORMSS
Copy link

WORMSS commented Jun 27, 2019

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants