JavaScript的`.sort()`未定义的值应始终为”earlier”。

huangapple go评论55阅读模式
英文:

JavaScript .sort() undefined value always should be "earlier"

问题

我想按多个字段对对象数组进行排序(在我的情况下为3-4个字段)。对象的某些值可能为undefined,这些值必须始终在排序中位于"更早"的位置(升序和降序)。在我的情况下,当排序为降序时,一切都正常工作,但在升序值的情况下,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)
     );
英文:

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

答案1

得分: 1

只需编写您自己的比较函数。0 表示它们相同,正数表示 b 应该排在前面,负数表示 a 应该排在前面。

英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const localeCompareUndefined = (a, b, locales, options) =&gt; {
  if (a === undefined &amp;&amp; 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: &quot;1&quot;, label: &quot;Z&quot;, code: &quot;Z&quot;}, 
 {id: &quot;1&quot;, code: &quot;A&quot;},
 {id: &quot;2&quot;, label: &quot;A&quot;,},
 {id: &quot;3&quot;, label: &quot;A&quot;, code: &quot;A&quot;}]
.sort((a, b) =&gt; {
  return localeCompareUndefined(a.id, b.id) ||
    localeCompareUndefined(a.label, b.label) ||
    localeCompareUndefined(a.code, b.code)
});

console.log(data);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 16:04:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定