以下函数执行以下操作:
1) 如果 isDefault === true
和 isDefault === false
,则前者优先。
2) 如果 isDefault === true
和 isDefault === true
,按 updatedAt
降序排序。
3) 如果 isDefault === false
和 isDefault === false
,按 name
升序排序。
function sortPanoramas (panoramas) {
panoramas.sort((a, b) => {
if (a.isDefault !== b.isDefault) return a.isDefault < b.isDefault
if (a.isDefault && b.isDefault) return a.updatedAt < b.updatedAt
if (!a.isDefault && !b.isDefault) return a.name > b.name
})
}
这在 Chrome 中有效,但在 Safari 中无效,因为有人告诉我你应该在 sort
函数中返回数字。
如何修改函数使其返回数字?
编辑:示例数据:
[
{
"id": "CbU2Z5BZ9w",
"name": "a01",
"updatedAt": "2016-08-24T06:20:47.972Z",
"isDefault": true,
"index": 0
},
{
"id": "RdT5CvGLRg",
"name": "a02",
"updatedAt": "2016-08-24T06:21:22.126Z",
"isDefault": false,
"index": 1
},
{
"id": "eHyt1TYcBN",
"name": "a03",
"updatedAt": "2016-08-24T06:21:47.404Z",
"isDefault": false,
"index": 2
},
{
"id": "jUTmyn2TDR",
"name": "a04",
"updatedAt": "2016-08-24T06:26:29.591Z",
"isDefault": false,
"index": 3
},
{
"id": "VGXXNcBMcH",
"name": "a05",
"updatedAt": "2016-08-24T06:27:12.934Z",
"isDefault": false,
"index": 4
}
]
最佳答案
我想这就是你需要的:
function sortPanoramas(panoramas) {
panoramas.sort((a, b) => {
if (a.isDefault !== b.isDefault) {
return a.isDefault ? -1 : 1;
}
if (a.isDefault && b.isDefault) {
return a.updatedAt > b.updatedAt ? -1 : a.updatedAt < b.updatedAt ? 1 : 0;
}
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});
}
关于javascript - 修改以下排序函数,使其返回数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39116267/