1

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.

6
  • 3
    please add the data as well. Commented May 2, 2017 at 9:57
  • By "always" you mean "regardless of sortdir"? Commented May 2, 2017 at 9:58
  • Instead of -99e+10 (which might be the smallest number you can imagine), one should use -Infinity Commented May 2, 2017 at 9:59
  • by always i mean when you sort in asc should be 1,2,3 NULL at end or desc 5,4,3,2,1 NULL at the end also. Data are just some random numbers Commented May 2, 2017 at 10:00
  • i cant use answer down i have to overwrite my function Commented May 2, 2017 at 10:08

2 Answers 2

3

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; }

Sign up to request clarification or add additional context in comments.

4 Comments

Nice! Very elegant solution with plain JavaScript.
can you help me to overwrite my function because is slickgrid plugin function
but there is one function to sort asc or desc
@vladimirProp, you could utilize the given sortorder of the wanted column.
0

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

3 Comments

where to return 0
please don't just show the code. give explanation as how it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.