# 面试官：如何对字符串版本号构成的数组进行排序？

const arr=['0.1.1', '2.3.3', '0.302.1', '4.2', '4.3.5', '4.3.4.5'];
arr.sort((a,b)=>a>b?-1:1);
console.log(arr); // ['4.3.5','4.3.4.5','2.3.3','0.302.1','0.1.1']

## 为什么字符串比较能够轻松的实现排序？

console.log('5'>'1')
console.log('5'>'10')

const arr=[
'0.5.1',
'0.1.1',
'2.3.3',
'0.302.1',
'4.2',
'4.3.5',
'4.3.4.5'
];

## “大数”加权法

### 比较npm规则版本号

const arr=['2.3.3', '4.3.4', '0.3.1'];

MAJOR*p2 + MINOR*p + PATCH

const p = 1000;
const gen = (arr) =>
arr.split('.').reduce(reducer,0);

const reducer = (acc,value,index) =>
acc+(+value)*Math.pow(p,arr.length-index-1);

arr.sort((a,b)=> gen(a)>gen(b)?-1:1);

console.log(arr)

### 更多的版本号

const arr=[
'1.1',
'2.3.3',
'4.3.5',
'0.3.1',
'0.302.1',
'4.20.0',
'4.3.5.1',
'1.2.3.4.5'
];

const maxLen = Math.max(
...arr.map((item)=>item.split('.').length)
);

const reducer = (acc,value,index) =>
acc+(+value)*Math.pow(p,maxLen-index-1);

const gen = (arr) =>
arr.split('.').reduce(reducer,0);

arr.sort((a,b)=> gen(a)>gen(b)?-1:1);

console.log(arr)

## 循环比较法

arr.sort((a, b) => {
let i = 0;
const arr1 = a.split('.');
const arr2 = b.split('.');

while (true) {
const s1 = arr1[i];
const s2 = arr2[i++];

if (s1 === undefined || s2 === undefined) {
return arr2.length - arr1.length;
}

if (s1 === s2) continue;

return s2 - s1;
}
});

console.log(arr)

• 字符串比较法
• 大数加权法
• 循环比较法