- 作者:约克
- 原文地址:https://yorkyu.cn/use-ts-to-sort-multiple-version-numbers-1b104f681262.html
- 文章版权归作者所有,转载请注明出处!
版本号排序
例如现在存在一组版本号,[{version: "0.12.0.2"}, {version: "0.1.0.2"}]
,按 version 排序后的结果为 [{version: "0.1.0.2"}, {version: "0.12.0.2"}]
。
interface Src {
version: string;
system: iOS | Android;
name: string;
}
function versionSort(src: Src[] = [], orderKey?: string = 'version'): Src[] {
return src.sort((a, b) => {
let i = 0;
let arrA = [];
let arrB = [];
const aType = typeof a;
const bType = typeof b;
if (aType !== bType) {
return;
}
if (aType === 'object') {
arrA = a[orderKey].split('.');
arrB = b[orderKey].split('.');
}
while (true) {
const sA = arrA[i];
const sB = arrB[i ];
if (sA === undefined || sB === undefined) {
return arrB.length - arrA.length;
}
if (sA === sB) continue;
return sB - sA;
}
});
}
const data: Src[] = [
{
version: '0.12.0.2',
system: 'iOS',
name: 'v0.12.0.2',
},
{
version: '1.12.2.2',
system: 'iOS',
name: 'v1.12.2.2',
},
{
version: '0.15.78',
system: 'iOS',
name: 'v0.15.78',
},
{
version: '0.10.78',
system: 'iOS',
name: 'v0.10.78',
}
];
console.log(versionSort(data));
参考
- [1] js判断对多个版本号进行排序怎么做?