-1
我想按三個值排序此JavaScript數組,但我似乎無法弄清楚如何一次對多個屬性進行排序。按3個值對JavaScript數組進行排序
的要求是:
featured
項目應該是在最高層- 然後項目進行沒有名(
null
) - 然後用姓名的項目是不
featured
- 按
createdAt
降序排序(從最新的優先排序)
這是數組:
var items [
{ name: 'foo-1', featured: true, createdAt: 1493000001 },
{ name: null, featured: false, createdAt: 1493000003 },
{ name: 'foo-3', featured: true, createdAt: 1493000002 },
{ name: 'foo-4', featured: false, createdAt: 1493000004 },
{ name: 'foo-5', featured: false, createdAt: 1493000005 },
];
結果應該是:
[
{ name: 'foo-3', featured: true, createdAt: 1493000002 },
{ name: 'foo-1', featured: true, createdAt: 1493000001 },
{ name: null, featured: false, createdAt: 1493000003 },
{ name: 'foo-5', featured: false, createdAt: 1493000005 },
{ name: 'foo-4', featured: false, createdAt: 1493000004 },
]
已經回答[如何排序多個字段對象數組?](HTTP的=> http://stackoverflow.com/a/4760279/1315419 – Vasan
可能重複:/ /stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) –
@Vasan是的,這個答案真的很好 - http://stackoverflow.com/a/ 4760279/2957677 –