vladimirProp
vladimirProp

Reputation: 251

Sort javascript array null value always at bottom

Hey i am using slickgrid plugin and there i have function sortNumeric to sort data in order

function sorterNumeric(a, b) {
      var x = (isNaN(a[sortcol]) || a[sortcol] === "" || a[sortcol] === null) ? -99e+10 : parseFloat(a[sortcol]);
      var y = (isNaN(b[sortcol]) || b[sortcol] === "" || b[sortcol] === null) ? -99e+10 : parseFloat(b[sortcol]);
      return sortdir * (x === y ? 0 : (x > y ? 1 : -1));
    }

Can someone help me to extend this sorting, so null values comes always at last place.

Upvotes: 1

Views: 754

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could use the result of the comparison as value for the needed delta.

In SlickGrid, you get the sort order with the property sortAsc of the wanted cols to sort. then just use the closure over the sorting direction.

function sortFn(sortAsc) {
    return function (a, b) {
        return (a[sortcol] === null) - (b[sortcol] === null) || (sortAsc || -1) * (a[sortcol] - b[sortcol]);
    }
}

var array = [{ a: 1 }, { a: 3 }, { a: 2 }, { a: 8 }, { a: null }, { a: 42 }, { a: null }],
    sortcol = 'a';

array.sort(sortFn(true));  // asc
console.log(array);

array.sort(sortFn(false)); // desc
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Quickitdotnet
Quickitdotnet

Reputation: 1

You can use following code:

var sortcol = "num";
var sortdir = -1;

function sorterNumeric(a, b) {
    var x = (isNaN(a[sortcol]) || !a[sortcol]) ? 99e+10 * sortdir : parseFloat(a[sortcol]);
    var y = (isNaN(b[sortcol]) || !b[sortcol]) ? 99e+10 * sortdir : parseFloat(b[sortcol]);
    return x > y ? 1 * sortdir : -1 * sortdir;
}

var arr = [{ num: 1 }, { num: 3 }, { num: null }, { num: 7 }, { num: 2 } ]

Upvotes: 0

Related Questions