[英]How to sort JavaScript string array
I have the following array: 我有以下数组:
var arr = ["COL10","COL5",
"COL4","COL3",
"COL8","COL9",
"COL2","COL7",
"COL1","COL6"];
console.log("After sort:"+arr.sort());
The output is: 输出是:
After sort:COL1,COL10,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9
But I want it to be: 但我希望它是:
After sort:COL1,COL2,COL3,COL4,COL5,COL6,COL7,COL8,COL9,COL10
How should I do this? 我该怎么做?
Use the following approach with Array.sort
and String.slice
functions: 对Array.sort
和String.slice
函数使用以下方法:
var arr = ["COL10","COL5","COL4","COL3","COL8","COL9","COL2","COL7","COL1","COL6"]; arr.sort(function (a,b) { return a.slice(3) - b.slice(3); }); console.log(arr);
You could split the items and sort the parts separate. 您可以拆分项目并将各个部分分开。
var arr = ["COL10", "COL5", "COL4", "COL3", "COL8", "COL9", "COL2", "COL7", "COL1", "COL6"]; arr.sort(function (a, b) { var aa = a.split(/(\\d+)/g), bb = b.split(/(\\d+)/g); return aa[0].localeCompare(bb[0]) || aa[1] - bb[1]; }); console.log(arr);
Try out the alphanumerical sort from Brian Huisman: Article 试试Brian Huisman的字母数字排序: 文章
var arr = ["COL10", "COL5", "COL4", "COL3", "COL8", "COL9", "COL2", "COL7", "COL1", "COL6" ]; console.log("After sort:" + arr.sort(alphanum)); function alphanum(a, b) { function chunkify(t) { var tz = [], x = 0, y = -1, n = 0, i, j; while (i = (j = t.charAt(x++)).charCodeAt(0)) { var m = (i == 46 || (i >= 48 && i <= 57)); if (m !== n) { tz[++y] = ""; n = m; } tz[y] += j; } return tz; } var aa = chunkify(a); var bb = chunkify(b); for (x = 0; aa[x] && bb[x]; x++) { if (aa[x] !== bb[x]) { var c = Number(aa[x]), d = Number(bb[x]); if (c == aa[x] && d == bb[x]) { return c - d; } else return (aa[x] > bb[x]) ? 1 : -1; } } return aa.length - bb.length; }
var arr = ["COL10","COL5",
"COL4","COL3",
"COL8","COL9",
"COL2","COL7",
"COL1","COL6"];
arr.sort(function(a,b) {
var a1 = parseInt(a.split('COL')[1]);
var b1 = parseInt(b.split('COL')[1]);
return a1 - b1;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.