我有一个如下所示的JavaScript对象数组。
players = [{"player": "CR7", "status": false, "fullname": "Cristiano Ronaldo"},
{"player": "NJR11", "status": false, "fullname": "Neymar Jr."},
{"player": "SC11", "status": false, "fullname": "Sunil Chhetri"},
{"player": "LM10", "status": true, "fullname": "Lionel Messi"},
{"player": "SG19", "status": false, "fullname": "Sergio Aguero"}
];
我还使用下面的方法对数组进行排序。我的预期结果是状态为true
的对象应该首先出现,其余对象保持顺序。
players.sort((p) => (p.status) ? -1 : 1);
可以在Google Chrome中正常运行,如下所示。
[{"player":"LM10","status":true,"fullname":"Lionel Messi"},
{"player":"CR7","status":false,"fullname":"Cristiano Ronaldo"},
{"player":"NJR11","status":false,"fullname":"Neymar Jr."},
{"player":"SC11","status":false,"fullname":"Sunil Chhetri"},
{"player":"SG19","status":false,"fullname":"Sergio Aguero"}
]
但是在Mozilla Firefox和Android默认浏览器中,如下所示,这不是我想要的。
[{"player":"LM10","status":true,"fullname":"Lionel Messi"},
{"player":"SG19","status":false,"fullname":"Sergio Aguero"},
{"player":"SC11","status":false,"fullname":"Sunil Chhetri"},
{"player":"NJR11","status":false,"fullname":"Neymar Jr."},
{"player":"CR7","status":false,"fullname":"Cristiano Ronaldo"}
]
为什么它在Firefox中的行为有所不同?与Chrome一样工作的解决方案是什么?
答案 0 :(得分:3)
对于布尔值,您需要进行反向排序,因为true
被解释为1
,而false
为零。
要首先获取true
值,您需要从b
中减去a
。
var players = [{ player: "CR7", status: false, fullname: "Cristiano Ronaldo" }, { player: "NJR11", status: false, fullname: "Neymar Jr." }, { player: "SC11", status: false, fullname: "Sunil Chhetri" }, { player: "LM10", status: true, fullname: "Lionel Messi" }, { player: "SG19", status: false, fullname: "Sergio Aguero" }];
players.sort((a, b) => b.status - a.status); true frist
console.log(players);
您提供了另一种通过回调的解决方案。
var players = [{ player: "CR7", status: false, fullname: "Cristiano Ronaldo" }, { player: "NJR11", status: false, fullname: "Neymar Jr." }, { player: "SC11", status: false, fullname: "Sunil Chhetri" }, { player: "LM10", status: true, fullname: "Lionel Messi" }, { player: "SG19", status: false, fullname: "Sergio Aguero" }],
sortBy = p => p.status ? -1 : 1; // true first
players.sort((a, b) => sortBy(a) - sortBy(b));
console.log(players);
答案 1 :(得分:1)
您基本上是在改组数组。它改变了您期望它在Chrome中偶然排序的方式。您的排序根本不起作用。 sort
毕竟有两个要比较的元素:
players.sort((a, b) => b.status - a.status);
这是以下内容的简称:
players.sort((a, b) => {
if(a.status === b.status) return 0; // order doesnt matter
if(a.status) return -1; // only a has status, comes first
if(b.status) return 1 // only b has status, comes first
});
或者:
players = [...players.filter(it => it.status), ...players.filter(it => !it.status)];
可以更快,具体取决于引擎使用的排序算法。