我正在为体育赛事做一个 php 应用程序,在某些情况下得分最低的就是赢家。就像如果有 100 米运行比赛,那么获胜者就是跑得最快的。获胜者用最少的时间完成比赛。
但我面临的是,当有人缺席或在完成前退出时,我们将提供零分。在那种情况下,当我们要排序时,第一位将是零。但那应该是最后。
下面是我的javascript代码
var sorted = $(".result").sort(function (ib1, ib2) {
return parseFloat($(ib2).val()) - parseFloat($(ib1).val());
});
// Result Names
$('#result_first').val($("#participant"+$(sorted.get(9)).data("section")).val());
$('#result_second').val($("#participant"+$(sorted.get(8)).data("section")).val());
$('#result_third').val($("#participant"+$(sorted.get(7)).data("section")).val());
$('#result_fourth').val($("#participant"+$(sorted.get(6)).data("section")).val());
$('#result_fifth').val($("#participant"+$(sorted.get(5)).data("section")).val());
$('#result_sixth').val($("#participant"+$(sorted.get(4)).data("section")).val());
$('#result_seventh').val($("#participant"+$(sorted.get(3)).data("section")).val());
$('#result_eighth').val($("#participant"+$(sorted.get(2)).data("section")).val());
$('#result_ninth').val($("#participant"+$(sorted.get(1)).data("section")).val());
$('#result_tenth').val($("#participant"+$(sorted.get(0)).data("section")).val());
// Result Numbers
$('#result_first_no').val($(sorted.get(9)).val());
$('#result_second_no').val($(sorted.get(8)).val());
$('#result_third_no').val($(sorted.get(7)).val());
$('#result_fourth_no').val($(sorted.get(6)).val());
$('#result_fifth_no').val($(sorted.get(5)).val());
$('#result_sixth_no').val($(sorted.get(4)).val());
$('#result_seventh_no').val($(sorted.get(3)).val());
$('#result_eighth_no').val($(sorted.get(2)).val());
$('#result_ninth_no').val($(sorted.get(1)).val());
$('#result_tenth_no').val($(sorted.get(0)).val());
请帮我对这些值进行排序,零值应该排在最后。
最佳答案
这里的基本思想是将 0
视为 Infinity
:
var sorted = $(".result").sort(function (ib1, ib2) {
function value(el) {
var x = parseFloat($(el).val());
return x === 0 ? Infinity : x;
}
return value(ib2) - value(ib1);
});
一个简单的测试:
var sorted = [5, 2, 0, 9, 4].sort(function(ib1, ib2) {
function value(el) {
var x = el; // parseFloat($(el).val());
return x === 0 ? Infinity : x;
}
return value(ib2) - value(ib1);
});
console.log(sorted);
关于javascript - 想要按升序对数组进行排序,但零应该在最后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44942070/