我有一个对象数组。
let items = [
{ name: 'eric', type: 'comparable', value: 1 },
{ name: 'bob', type: 'comparable', value: 4 },
{ name: 'michael', type: 'comparable', value: 0 },
{ name: 'john', type: 'comparable', value: 3 },
{ name: 'brad', type: 'incomparable', value: null },
{ name: 'james', type: 'incomparable', value: 5},
{ name: 'martin', type: 'comparable', value: 2 },
{ name: 'chris', type: 'comparable', value: null }
];
我想对我的数组进行排序,这样就可以对对象进行排序。
首先, 根据 "type "属性 -> 如果是 "Comparable" -> 根据 "value "属性进行排序。
二、根据 "value "属性->如果是null就把它放在数组的底部
的 "value "属性,如果是空的,就把数组底部的对象,做成这样。
{ name: 'michael', type: 'comparable', value: 0 },
{ name: 'eric', type: 'comparable', value: 1 },
{ name: 'martin', type: 'comparable', value: 2 },
{ name: 'john', type: 'comparable', value: 3 },
{ name: 'bob', type: 'comparable', value: 4 },
{ name: 'chris', type: 'comparable', value: null },
{ name: 'brad', type: 'incomparable', value: null },
{ name: 'james', type: 'incomparable', value: 5}
我已经这样做了:
items.sort((a, b) => {
return (a.value===null)-(b.value===null) || +(a.value>b.value)||-(a.ordre<b);
});
但我总是根据 "value "属性进行排序,我希望它先查找属性。
(我不会使用loadash)
有什么建议?
我个人认为,如果逻辑读起来和你描述的方式类似,就更容易读懂。在这个例子中,我试图将你描述的需求转化为一系列的 if
语句,而不是单一的逻辑表达式。
let items = [
{ name: 'eric', type: 'comparable', value: 1 },
{ name: 'bob', type: 'comparable', value: 4 },
{ name: 'michael', type: 'comparable', value: 0 },
{ name: 'john', type: 'comparable', value: 3 },
{ name: 'brad', type: 'incomparable', value: null },
{ name: 'james', type: 'incomparable', value: 5},
{ name: 'martin', type: 'comparable', value: 2 },
{ name: 'chris', type: 'comparable', value: null }
];
console.log(items.sort((a, b) => {
if (a.type === 'comparable' && b.type === 'comparable') {
if (a.value == null) return 1;
return a.value - b.value;
}
if (a.type === 'comparable') return -1;
return 1;
}));
你可以做一个 localeCompare
的 type
,然后在类型相同的情况下做一个布尔短路。在表达式的第二部分,你可以计算出 value
,胁迫性 null
到 Infinity
将其移至最后。
const items = [
{ name: 'eric', type: 'comparable', value: 1 },
{ name: 'bob', type: 'comparable', value: 4 },
{ name: 'michael', type: 'comparable', value: 0 },
{ name: 'john', type: 'comparable', value: 3 },
{ name: 'brad', type: 'incomparable', value: null },
{ name: 'james', type: 'incomparable', value: 5},
{ name: 'martin', type: 'comparable', value: 2 },
{ name: 'chris', type: 'comparable', value: null }
];
items.sort((a, b) => a.type.localeCompare(b.type)
|| (a.value != null ? a.value : Infinity) - (b.value != null ? b.value : Infinity));
console.log(items);