Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort javascript array so that blank values are always at bottom

So I have an array of arrays which contain only strings. The array of arrays is to be displayed as a table and may have over 1000 rows with 20 or more values in each.

eg:

var arr = [
    ["bob","12","yes"],
    ["joe","","no"],
    ["tim","19","no"],
    ["dan","","yes"],
    ["tim","",""],
    ["dan","0",""]
]

the strings may contain anything that can be represented as a string, including: " ", "", "0" or "00-00-00" etc... and any column my be used for ordering.

I am sorting the arrays ascending and descending but some of the values I am sorting by are blank strings: "". How could I get the blank strings (only) to always be at the end of the new arrays in all modern browsers?

currently they are at the end when ascending but at the start when descending.

I am sorting like below (Yes I'm sure I can do it shorter too):

if (direction == "asc") {
    SortedArr = arr.sort(function (a, b) {
        if (a[colToSortBy] == '') {
            return -1;
        }
        if (a[colToSortBy].toUpperCase() < b[colToSortBy].toUpperCase()) {
            return -1;
        }
        if (a[colToSortBy].toUpperCase() > b[colToSortBy].toUpperCase()) {
            return 1;
        }
        return 0;
    });
} else {
    SortedArr = arr.sort(function (a, b) {
        if (a[colToSortBy] == '') {
            return -1;
        }
        if (b[colToSortBy].toUpperCase() < a[colToSortBy].toUpperCase()) {
            return -1;
        }
        if (b[colToSortBy].toUpperCase() > a[colToSortBy].toUpperCase()) {
            return 1;
        }
        return 0;
    });
}
like image 759
Chris J Avatar asked Nov 24 '11 11:11

Chris J


2 Answers

Empty strings at the end

Working example on JSFiddle that puts empty strings always at the end no matter whether order is ascending or descending. This may be a usability issue, but this is the solution:

if (direction == "asc") {
    SortedArr = arr.sort(function (a, b) {
        return (a[col] || "|||").toUpperCase().localeCompare((b[col] || "|||").toUpperCase())
    });
} else {
    SortedArr = arr.sort(function (a, b) {
        return (b[col] || "!!!").toUpperCase().localeCompare((a[col] || "!!!").toUpperCase())
    });
}
like image 107
Robert Koritnik Avatar answered Oct 22 '22 20:10

Robert Koritnik


I think your problem comes from the fact that you're checking if a[colToSortBy] is an emtpy string but you don't do it for b[colToSortBy].

like image 29
Rodolphe Avatar answered Oct 22 '22 19:10

Rodolphe