简体   繁体   中英

javascript custom sort when parts of an array has no data

I have an object model that looks like this:

MyObject = {
   TheName: "",
   OtherProps :....
}

I have an array of these objects and my custom sort function looks like this:

function SortArray() {

  var CustomFunction;

  var CustomSortAsc = function (a, b) {
    return a['TheName'] - b['TheName'];
  }

  var CustomSortDsc = function (a, b) {
    return b['TheName'] - a['TheName'];
  }

  if (SomeCondition) {
      CustomFunction = CustomSortAsc;
  } else {
      CustomFunction = CustomSortDsc;
  }

  SomeArray.sort(CustomFunction);
}

SomeArray has somewhere around 200-300 objects in it and the problem is that sometimes the object has an empty TheName property. Because of that, the sort doesn't seem to work as expected. For instance, if there are values then sort by name and then put all the values for which there are no names according to the sort function.

What's the way to make this work? Thanks for your suggestions.

As your TheNames are strings, you probably better use localeCompare instead:

var CustomSortAsc = function(a, b) {
    return (a['TheName'] || '').localeCompare(b['TheName'] || '');
};

And I'll probably write it all like this:

var baseSort = function(a, b) { 
  return (a['TheName'] || '').localeCompare(b['TheName'] || '');
};
var CustomFunction = SomeCondition 
                   ? baseSort 
                   : function(a, b) { return -baseSort(a, b); };

UPDATE: and if you need to see the empty values the last all the time...

var CustomSortAsc = function(a, b) {
    return a['TheName'] === '' 
         ? b['TheName'] === ''
           ? 0
           : 1
         : b['TheName'] === ''
           ? -1
           : a['TheName'].localeCompare(b['TheName']); 
};

... or, if you prefer if :

if (a['TheName'] === '') {
  if (b['TheName'] === '') {
    return 0;
  } else {
    return 1;
  }
} else {
  if (b['TheName'] === '') {
    return -1;
  } else {
    return a['TheName'].localeCompare(b['TheName']);
  }
}

(is this actually more readable?)

A custom sort function must return a number (<,= or > 0). If it returns anything else (like NaN ), the behaviour is "implementation specific" (according to the standard), which means it usually breaks and just sorts nothing.

I'm not sure what you are trying to sort for ('TheName' sounds like strings, your function is for numbers), but you should just return 1 if the property does not exist on b and -1 if on a; then your property-less items will be sorted to the end of the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM