Linq.JS OrderBy with null values

4.6k views Asked by At

I would like to order my data by the date, but some of the date values are null. How would I go about ordering the data and have the null values be together at the end of my list for descending and the beginning of my list for ascending?

Javascript:

var data = [
    {"n": "Adams","v": null},
    {"n": "Anderson","v": "2015-05-30T15:07:00.0000000"},
    {"n": "Armstrong","v": "2015-06-06T02:09:00.0000000"},
    {"n": "Cooper","v": "2015-06-06T02:12:00.0000000"},
    {"n": "House","v": "2015-06-12T12:33:00.0000000"},
    {"n": "Lee","v": "2015-06-06T00:59:00.0000000"},
    {"n": "Marmol","v": "2015-06-06T23:22:00.0000000"},
    {"n": "Maronde","v": "2015-06-06T16:46:00.0000000"},
    {"n": "Molleken","v": "2015-06-06T16:51:00.0000000"},
    {"n": "Murata","v": "2015-06-06T23:20:00.0000000"},
    {"n": "Price","v": null},
    {"n": "Roth","v": "2015-06-07T14:00:00.0000000"},
    {"n": "Soto","v": "2015-06-06T23:46:00.0000000"}
];

var enu = $.Enumerable.From(data)
    .OrderBy('$.v')
    .Select()
    .ToArray();
var vue = new Vue({
    el: 'ul',
    data: {
        title: 'test',
        test: enu
    }
});

HTML:

<ul>
    <li v-repeat="test">{{v}}</li>
</ul>

Output:

null
2015-05-30T15:07:00.0000000
2015-06-06T00:59:00.0000000
2015-06-06T02:09:00.0000000
2015-06-06T02:12:00.0000000
2015-06-06T16:46:00.0000000
2015-06-06T16:51:00.0000000
2015-06-06T23:20:00.0000000
2015-06-06T23:22:00.0000000
2015-06-06T23:46:00.0000000
2015-06-12T12:33:00.0000000
null
2015-06-07T14:00:00.0000000

See my fiddle: https://jsfiddle.net/6pcmq89h/

You can see how the null items separate the dates and I'm not sure why this is happening. Can anyone help?

Edit: The solution can't have anything hardcoded because I am going to dynamically change the column to sort when clicking header titles. The issue of the null values should work regardless of data type. As long as there is null values, I need them to be grouped together.

Thanks!

1

There are 1 answers

0
Jeff Mercado On BEST ANSWER

Just add in a placeholder value for the cases when it is null. Since you're ordering in descending order and you want it in the end, give them the smallest values possible. You might want to add a thenby clause afterwards.

var enu = $.Enumerable.From(data)
    .OrderByDescending("$.v || '0000'")
    .ThenBy("$.n")
    .ToArray();

fiddle