使用ocaleCompare进行排序后,发现排序后的顺序是这样的(为什么会这样排序,可以自己去研究一下),但这并不是自己想要的。期望顺序:A-11,A-22,A-111,A-222
在网上查找了半天,终于找到了一个可以解决这个问题的代码,直接拿过来套用
function compare() {
return (a, b) => {
const aName = a.devName;
const bName = b.devName;
if (aName && bName) {
const isNumber = (v) => (+v).toString() === v;
const aPart = aName.match(/\d+|\D+/g);
const bPart = bName.match(/\d+|\D+/g);
let i = 0;
const len = Math.min(aPart.length, bPart.length);
while (i < len && aPart[i] === bPart[i]) {
i++;
}
if (i === len) {
return aPart.length - bPart.length;
}
if (isNumber(aPart[i]) && isNumber(bPart[i])) {
return aPart[i] - bPart[i];
}
return aPart[i].localeCompare(bPart[i]);
}
};
},
[{devName:'A-22'},{devName:'A-11'},{devName:'A-111'},{devName:'A-222'}].sort(compare());