英文:
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) => {
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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论