COMMUNITY

More brief convenient way to sort an array?

I see that to sort an array, we can do:

a.sort(
    (a, b) -> {
        if (a < b) return -1;
        else if (a > b) return 1;
        return 0;
    }
);

For convenience, is there a built-in comparison function for that? That is, something like

a.sort(Std.cmp);

?

There is Reflect.compare which does just that.

1 Like

Reflect.compare carries a overhead if you just want to compare integers.
This is better:

arr.sort((a,b) -> a - b);
2 Likes

You also might want to take a look at

1 Like

Remember that only the sign of the value returned by a sort-compare function determines the outcome: that it is positive, zero, or negative. So, a - b works very nicely … if a comparison subroutine is needed at all.

Basically, you need a comparison routine [only] when, for instance, sorting structures of some kind, or sorting by more than one key.

Well, you need some sorting function. a.sort() errors out, reporting that it expects a function as an argument.

use the force https://github.com/jasononeil/cleversort

1 Like