-1

I want to sort an array of objects by multiple fields (3-4 in my case). Some values of object could be undefined and those values must be always "earlier" in sorting (ascending and descending). In my case everything works when sorting is descending, but in case of ascending values which are undefined are always in the bottom. Type of those values is always a string and I could call only .sort() method nothing before it and after. My code looks like this:

[{id: "1", label: "Z", code: "Z"}, 
 {id: "1", code: "A"},
 {id: "2", label: "A",},
 {id: "3", label: "A", code: "A"}]
     .sort((a,b) => {
          return a.id.localeCompare(b.id)
             || a.label.localeCompare(b.label)
             || a.code.localeCompare(b.code)
     );
zzzzz
  • 222
  • 2
  • 7

1 Answers1

1

Just write your own comparison function. 0 means they're the same, a positive number means b should come first, a negative number means a should come first.

const localeCompareUndefined = (a, b, locales, options) => {
  if (a === undefined && b === undefined) return 0;
  else if (b === undefined) return 1;
  else if (a === undefined) return -1;
  else return a.localeCompare(b, locales, options);
}

const data = [{id: "1", label: "Z", code: "Z"}, 
 {id: "1", code: "A"},
 {id: "2", label: "A",},
 {id: "3", label: "A", code: "A"}]
.sort((a, b) => {
  return localeCompareUndefined(a.id, b.id) ||
    localeCompareUndefined(a.label, b.label) ||
    localeCompareUndefined(a.code, b.code)
});

console.log(data);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34