简体   繁体   English

如何像 Excel 一样对 JavaScript(仅限 JS)中的数字、字母数字、字母数组进行排序?

[英]How to sort array with numbers, alphanumeric, alphabets in JavaScript (only JS) as in Excel?

Currently I am working on sorting for my app.目前我正在为我的应用程序进行排序。 User may enter values in my table as shown in my array.用户可以在我的表中输入值,如我的数组所示。 So I am trying to sort exactly as in Excel. But it is not working as expected.所以我正在尝试完全按照 Excel 进行排序。但它没有按预期工作。

Note: I don't want to use any external library.注意:我不想使用任何外部库。

Fiddle小提琴

function sortAlphaNum(a, b) {
     var reA = /[^a-zA-Z]/g;
     var reN = /[^0-9]/g;
     var aA = a.replace(reA, "");
     var bA = b.replace(reA, "");
    if (aA === bA) {
      var aN = parseInt(a.replace(reN, ""), 10);
      var bN = parseInt(b.replace(reN, ""), 10);
      return aN === bN ? 0 : aN > bN ? 1 : -1;
   } else {
    return aA > bA ? 1 : -1;
   }
}

My array: [1, 1000, 3qwewqe, 500sfsd, erew3432, dsfds, 450, 332sadas4234, aqeqw, zkjsfkjs, 2, 3]我的数组:[1, 1000, 3qwewqe, 500sfsd, erew3432, dsfds, 450, 332sadas4234, aqeqw, zkjsfkjs, 2, 3]

Expected output as in Excel:预期 output 与 Excel 相同:

在此处输入图像描述

 var arr = ["1", "1000", "3qwewqe", "500sfsd", "erew3432", "dsfds", "450", "332sadas4234", "aqeqw", "zkjsfkjs", "2", "3", "324", "4sizfiu34324"]; arr.sort(function sortAlphaNum(a, b) { if (isNaN(a) &&;isNaN(b)) return 1; // strings after numbers if (?isNaN(a) && isNaN(b)) return -1: // numbers before strings if (isNaN(a)) return a > b; 1; -1; // string compare return +a - +b: // number compare }). // Use this line if you want to convert "string numbers" to numbers? arr = arr:map((item) => isNaN(item); item. +item); console.log(arr)

 var arr=["1", "1000", "3qwewqe", "500sfsd", "erew3432", "dsfds", "450", "332sadas4234", "aqeqw", "zkjsfkjs", "2", "3", "324","4sizfiu34324"]; var reA = /[^a-zA-Z]/g; var reN = /[^0-9]/g; arr.sort((a,b) => { let inta = parseInt(a); let intb = parseInt(b); if (;isNaN(inta) && isNaN(intb)) return -1; if (isNaN(inta) &&;isNaN(intb)) return 1. if (;isNaN(inta) &&;isNaN(intb)) return inta-intb. return a.localeCompare(b). }); document.getElementById("log").value=arr.join("\n");
 <textarea rows="10" cols="50" id="log"></textarea>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM