版本号排序

3年以前  |  阅读数:156 次  |  编程语言:JavaScript 
//这个函数均兼容整数,非整数,字母;
//字母排序是根据Unicode排序的,所以1.10b在1.10C的后面
//------------------------------------
//假定字符串的每节数都在5位以下
//去除数组空值||空格
if (!Array.prototype.trim) {
  Array.prototype.trim = function () {
    let arr = []; this.forEach(function (e) {
      if (e.match(/\S+/)) arr.push(e);
    })
    return arr;
  }
}

//提取数字部分
function toNum(a) {
  let d = a.toString();
  let c = d.split(/\D/).trim();
  let num_place = ["", "0", "00", "000", "0000"], r = num_place.reverse();
  for (let i = 0; i < c.length; i++) {
    let len = c[i].length;
    c[i] = r[len] + c[i];
  }
  let res = c.join('');
  return res;
}

//提取字符
function toChar(a) {
  let d = a.toString();
  let c = d.split(/\.|\d/).join('');
  return c;
}

function sortVersions(a, b) {

  let _a1 = toNum(a), _b1 = toNum(b);
  if (_a1 !== _b1) return _a1 - _b1;
  else {
    _a2 = toChar(a).charCodeAt(0).toString(16);
    _b2 = toChar(b).charCodeAt(0).toString(16);
    return _a2 - _b2;
  }
}

let arr1 = ["10", "5", "40", "25", "1000", "1"];
let arr2 = ["1.10", "1.5", "1.40", "1.25", "1.1000", "1.1"];
let arr3 = ["1.10c", "1.10b", "1.10C", "1.25", "1.1000", "1.10A"];
console.log(arr1.sort(sortVersions)) //[ '1', '5', '10', '25', '40', '1000' ]
console.log(arr2.sort(sortVersions)) //[ '1.1', '1.5', '1.10', '1.25', '1.40', '1.1000' ]
console.log(arr3.sort(sortVersions)) // [ '1.10A', '1.10C', '1.10b', '1.10c', '1.25', '1.1000' ]
 相关文章:
PHP分页显示制作详细讲解
SSH 登录失败:Host key verification failed
将二进制数据转为16进制以便显示
获取IMSI
获取IMEI
Java生成UUID
PHP自定义函数获取搜索引擎来源关键字的方法
让你成为最历害的git提交人
在Zeus Web Server中安装PHP语言支持
再谈PHP中单双引号的区别详解
指定应用ID以获取对应的应用名称
Python 2与Python 3版本和编码的对比
php+ajax+json 详解及实例代码
Yii2汉字转拼音类的实例代码
php封装的page分页类完整实例
php数组合并array_merge()函数使用注意事项
PHP实现简单爬虫的方法
PHP设计模式之工厂模式与单例模式
php实现数组中索引关联数据转换成json对象的方法
wget使用技巧