JavaScript .sort()未定义值应始终为“更早”

nzkunb0c  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(109)

我想按多个字段对对象数组进行排序(在我的例子中是3-4)。object的一些值可能是undefined,并且这些值必须总是在排序中“靠前”(升序和降序)。在我的例子中,当排序是降序时一切都工作,但是在升序的情况下,未定义总是在底部。这些值的类型总是字符串,我只能调用.sort()方法之前和之后没有任何内容。我的代码如下所示:

[{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)
     );
bjp0bcyl

bjp0bcyl1#

只需编写自己的比较函数。0表示它们相同,正数表示b应该优先,负数表示a应该优先。

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

相关问题