12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- function sort_NUM_EN_CN(arr, filed, sort) {
- const isLetterOrNumberReg = function (str) {
- return /^[0-9a-zA-Z]+$/.test(str);
- }
- const isAllChineseStr = function (str) {
- return /^[\u4E00-\u9FA5]+$/.test(str);
- };
- const splitStringByNumber = function (str, sortByNumericalSize) {
- let strArr = [];
- const REG_STRING_NUMBER_PARTS = /\d+|\D+/g;
- const arr = str.match(REG_STRING_NUMBER_PARTS);
- for (let i = 0; i < arr.length; i++) {
- const splitStr = arr[i];
- if (isNaN(splitStr)) {
- strArr = strArr.concat(splitStr.split(''));
- } else {
- // Whether to split numbers
- if (!sortByNumericalSize) {
- strArr = strArr.concat(splitStr.split(''));
- } else {
- strArr.push(splitStr);
- }
- }
- }
- return strArr;
- }
- arr.sort(function (a, b) {
- // 都是数字或字母
- if (isLetterOrNumberReg(a[filed]) && isLetterOrNumberReg(b[filed])) {
- return a[filed].localeCompare(b[filed], 'zh-Hans-CN', { numeric: true });
- }
- // 中文字符串自己比较
- if (isAllChineseStr(a[filed]) && isAllChineseStr(b[filed])) {
- return a[filed].localeCompare(b[filed], 'zh-Hans-CN', { numeric: true });
- }
- const sortByNumericalSize = true;
- const arrA = splitStringByNumber(a[filed], sortByNumericalSize);
- const arrB = splitStringByNumber(b[filed], sortByNumericalSize);
- let result = 0;
- const length = Math.min(arrA.length, arrB.length);
- for (let i = 0; i < length; i++) {
- const charA = arrA[i];
- const charB = arrB[i];
- // 数字, 字符串排在 中文前面
- if (!isAllChineseStr(charA) && isAllChineseStr(charB)) {
- return -1;
- }
- if (isAllChineseStr(charA) && !isAllChineseStr(charB)) {
- return 1;
- }
- // 中文字符直接比较
- if (isAllChineseStr(charA) && isAllChineseStr(charB)) {
- result = charA.localeCompare(charB, 'zh-Hans-CN');
- } else {
- // 都不是中文
- result = charA.localeCompare(charB, 'zh-Hans-CN', { numeric: true });
- }
- if (result !== 0) {
- return result;
- }
- }
- if (arrA.length > arrB.length) return 1;
- if (arrA.length < arrB.length) return -1;
- return 0;
- })
- if (sort == "desc") {
- return arr.reverse()
- } else {
- return arr
- }
- }
|