Alan2
Alan2

Reputation: 24572

Sorting a javascript array when the value of a field can be null?

I have this function:

tests.sort(function (a, b) {
   var diff = a.title.localeCompare(b.title);
   return diff == 0 ? b.modifiedDate.localeCompare(a.modifiedDate) : diff;
});

I am using it to sort the tests array first by title and then by modifiedDate. The code was working but now I found it gives an error. When the modifiedDate is null and when this happens the compare fails.

How could I make it so that if the modifiedDate is null then the sort still works and places those rows after the rows with a modifiedDate that's not null?

Upvotes: 0

Views: 68

Answers (2)

vol7ron
vol7ron

Reputation: 42099

Thinking off the top of my head, to sort by title and then modifiedDate with nulls last:

tests.sort(function (a, b) {
   var diff = a.title.localeCompare(b.title),
       has_modifiedDate = a.modifiedDate && b.modifiedDate && true || false; 


  if (diff === 0) {
    if (has_modifiedDate) {
      return a.modifiedDate.localeCompare(b.modifiedDate)
    }
    else {
      if (! b.modifiedDate){
        if (! a.modifiedDate)
          return 0;
        else
          return -1;
      }
      else {
        if (! a.modifiedDate)
          return 1;
        else
          return -1;
      }
    }
  }
  else 
    return diff;
});

Note: this is untested and it's very late/early here. If this is incorrect, post and I'll delete or update; but way to tired to think.

Quick dataset you can try testing with; fill in with whatever data you want:

var tests = [
  {modifiedDate:'z',    title:'foo'},
  {modifiedDate:'a',    title:'foo'},
  {modifiedDate:null,   title:'foo'},
  {modifiedDate:'a',    title:'foo'},
  {modifiedDate:'null', title:'foo'},
  {modifiedDate:'z',    title:'foo'},
  {modifiedDate:'z',    title:'bar'},
  {modifiedDate:'a',    title:'bar'},
  {modifiedDate:null,   title:'bar'}
 ];

Upvotes: 1

Will
Will

Reputation: 1768

Try this:

tests.sort(function(a, b) {
    var diff = a.title.localeCompare(b.title);
    return diff == 0 ? (a.modifiedDate ? a.modifiedDate.getTime() : Infinity) - (b.modifiedDate ? b.modifiedDate.getTime() : Infinity) : diff;
})

Upvotes: 0

Related Questions