Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort JSON with JavaScript Alphabetical before Numerical

So I have some sort code that I wrote in JS, but it sorts numerical before alphabetical and I want it to do alphabetical before numerical. Here is a JSfiddle of it in action.

    var sort_by = function(field, reverse, primer){
var key = function(x) {return primer ? primer(x[field]) : x[field]};
return function(a,b) {
    var A = key(a), B = key(b);
    return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1,1][+!!reverse];
}

}

like image 893
Justin Avatar asked Aug 25 '26 08:08

Justin


1 Answers

var sort_by = function(field, reverse, primer){
    var key = function(x) {return primer ? primer(x[field]) : x[field]};
    var isNotNumber = function (x) { try {return isNaN(x.substr(0,1)); }catch(e){return false    ;}}
    var sorter = function(a,b) {
        var A = key(a), B = key(b);
        if ( !isNotNumber(A) && isNotNumber(B)) return -1;
        if ( isNotNumber(A) && !isNotNumber(B)) return +1;
        return ((A < B) ? -1 : (A > B) ? +1 : 0) * [-1,1][+!!reverse];
    }
    return sorter;
}
like image 101
Vlad Avatar answered Aug 26 '26 23:08

Vlad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!