我有一个字符数组,人们可以对其进行投票,并将选票存储在数组中。
我用它做了两个新的数组,我想对第一个数组进行排序,这样具有最佳上、下票比的字符(在从向上的票数中减去下降的票数后)就在数组的前面,而第二个字符应该正好相反。
我对第一个数组的比较函数是返回一个数组,其中Edward的比为2:1,下线率为2:1,而小悟空的比率为1:0,这是不正确的;它们应该在数组上领先于Edward。
const characters = [
{ name: 'Sharpe', upvotes: 2, downvotes: 0 },
{ name: 'Edward', upvotes: 4, downvotes: 2 },
{ name: 'Magnetic', upvotes: 1, downvotes: 0 },
{ name: 'The', upvotes: 1, downvotes: 0 },
{ name: 'Goku', upvotes: 2, downvotes: 0 },
{ name: 'Zeros', upvotes: 1, downvotes: 1 }
];
characters.sort((a, b) => {
return (b.upvotes - b.downvotes) - (a.upvotes - a.downvotes);
});
console.log(characters);
发布于 2022-03-10 06:25:17
const characters = [
{ name: 'Edward', upvotes: 21, downvotes: 30 },
{ name: 'Sharpe', upvotes: 37, downvotes: 200 },
{ name: 'And', upvotes: 45, downvotes: 3 },
{ name: 'The', upvotes: 0, downvotes: 0 },
{ name: 'Magnetic', upvotes: 1, downvotes: 0 },
{ name: 'Zeros', upvotes: 37, downvotes: 100 }
];
characters.sort((a, b) => {
if (a.downvotes == 0 && b.downvotes == 0) {
return b.upvotes - a.upvotes;
}
else if (a.downvotes == 0 && a.upvotes > 0) {
return -1;
}
else if (b.downvotes == 0 && b.upvotes > 0) {
return 1;
}
return (b.upvotes - b.downvotes) - (a.upvotes - a.downvotes);
});
console.log(characters);
https://stackoverflow.com/questions/47984993
复制相似问题