当属性不一致时,如何基于属性对JavaScript对象列表进行排序
我们有一个包含各种对象的数组。此数组上的一些对象具有日期字段(基本上从服务器以字符串形式返回,而不是日期对象),而对于其他对象,此字段为null。
要求是我们必须在顶部显示不带日期的对象,并且带日期的对象需要在按日期字段排序之后显示。
同样,对于没有日期的对象,需要按字母顺序进行排序。
示例
const sorter = ((a, b) => {
if (typeof a.date == 'undefined' && typeof b.date != 'undefined') {
return -1;
}
else if (typeof a.date != 'undefined' && typeof b.date == 'undefined') {
return 1; }
else if (typeof a.date == 'undefined' && typeof b.date == 'undefined') {
return a.name.localeCompare(b.name);
}
else if (a.date == null && b.date != null) {
return -1;
}
else if (a.date != null && b.date == null) {
return 1;
}
else if (a.date == null && b.date == null) {
return 0;
}
else {
var d1 = Date.parse(a.date);
var d2 = Date.parse(b.date);
return d1 - d2;
}
});热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短