sort-NUM-EN-CN.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. function sort_NUM_EN_CN(arr, filed, sort) {
  2. const isLetterOrNumberReg = function (str) {
  3. return /^[0-9a-zA-Z]+$/.test(str);
  4. }
  5. const isAllChineseStr = function (str) {
  6. return /^[\u4E00-\u9FA5]+$/.test(str);
  7. };
  8. const splitStringByNumber = function (str, sortByNumericalSize) {
  9. let strArr = [];
  10. const REG_STRING_NUMBER_PARTS = /\d+|\D+/g;
  11. const arr = str.match(REG_STRING_NUMBER_PARTS);
  12. for (let i = 0; i < arr.length; i++) {
  13. const splitStr = arr[i];
  14. if (isNaN(splitStr)) {
  15. strArr = strArr.concat(splitStr.split(''));
  16. } else {
  17. // Whether to split numbers
  18. if (!sortByNumericalSize) {
  19. strArr = strArr.concat(splitStr.split(''));
  20. } else {
  21. strArr.push(splitStr);
  22. }
  23. }
  24. }
  25. return strArr;
  26. }
  27. arr.sort(function (a, b) {
  28. // 都是数字或字母
  29. if (isLetterOrNumberReg(a[filed]) && isLetterOrNumberReg(b[filed])) {
  30. return a[filed].localeCompare(b[filed], 'zh-Hans-CN', { numeric: true });
  31. }
  32. // 中文字符串自己比较
  33. if (isAllChineseStr(a[filed]) && isAllChineseStr(b[filed])) {
  34. return a[filed].localeCompare(b[filed], 'zh-Hans-CN', { numeric: true });
  35. }
  36. const sortByNumericalSize = true;
  37. const arrA = splitStringByNumber(a[filed], sortByNumericalSize);
  38. const arrB = splitStringByNumber(b[filed], sortByNumericalSize);
  39. let result = 0;
  40. const length = Math.min(arrA.length, arrB.length);
  41. for (let i = 0; i < length; i++) {
  42. const charA = arrA[i];
  43. const charB = arrB[i];
  44. // 数字, 字符串排在 中文前面
  45. if (!isAllChineseStr(charA) && isAllChineseStr(charB)) {
  46. return -1;
  47. }
  48. if (isAllChineseStr(charA) && !isAllChineseStr(charB)) {
  49. return 1;
  50. }
  51. // 中文字符直接比较
  52. if (isAllChineseStr(charA) && isAllChineseStr(charB)) {
  53. result = charA.localeCompare(charB, 'zh-Hans-CN');
  54. } else {
  55. // 都不是中文
  56. result = charA.localeCompare(charB, 'zh-Hans-CN', { numeric: true });
  57. }
  58. if (result !== 0) {
  59. return result;
  60. }
  61. }
  62. if (arrA.length > arrB.length) return 1;
  63. if (arrA.length < arrB.length) return -1;
  64. return 0;
  65. })
  66. if (sort == "desc") {
  67. return arr.reverse()
  68. } else {
  69. return arr
  70. }
  71. }