项目中遇到多条件排序的需求,当时的第一反应是用冒泡排序,在第二层循环里去做多个判断,第一版写出的效果没有正常排序,而是乱序,后面得到高人指点,就此记录一下
第一版没有正常排序的原因是在判断完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; }