項目中遇到多條件排序的需求,當時的第一反應是用冒泡排序,在第二層循環里去做多個判斷,第一版寫出的效果沒有正常排序,而是亂序,后面得到高人指點,就此記錄一下
第一版沒有正常排序的原因是在判斷完fail_count后,后面的判斷沒有加
goodList[i].fail_count == goodList[j].fail_count以此類推
下面是正常排序后的代碼
handleGoodData: function (goodList) {
// 排序規則如下:
// 1.故障總次數小的拍前面(fail_count)
// 2.排序編號小的排前面(sort)
// 3.庫存大的排前面(stock)
// 4.貨道號小的排前面(channel)-- - 注意:服務器返回的channel是字符串格式為f0101,需要去掉首字母f之后才能按照數字進行比較
for (let i = 0; i < goodList.length; i++) {
for (let j = i + 1; j < goodList.length; j++) {
let temp = goodList[j];
if (goodList[i].fail_count > goodList[j].fail_count) {
goodList[j] = goodList[i];
goodList[i] = temp;
} else if (goodList[i].fail_count == goodList[j].fail_count && goodList[i].sort > goodList[j].sort) {
goodList[j] = goodList[i];
goodList[i] = temp;
} else if (goodList[i].fail_count == goodList[j].fail_count && goodList[i].sort == goodList[j].sort && goodList[i].stock < goodList[j].stock) {
goodList[j] = goodList[i];
goodList[i] = temp;
} else if (goodList[i].fail_count == goodList[j].fail_count && goodList[i].sort == goodList[j].sort && goodList[i].stock == goodList[j].stock) {
let front = goodList[i].channel.substring(1, goodList[i].channel.length);
let after = goodList[j].channel.substring(1, goodList[i].channel.length);
if (front > after) {
goodList[j] = goodList[i];
goodList[i] = temp;
}
}
}
}
return goodList;
}
