![](/img/trans.png)
[英]How can I replace certain data strings with predefined data using Javascript?
[英]How can I force certain strings to be sorted last in javascript?
我正在尝试按字母顺序对字符串数组进行排序,但某些字符串(例如"NA"
和"Wild"
)应始终放在最后。 排序优先级应为sorted_values_alphabetically < "NA" < "Wild"
。
如果我们有以下数组:
["Wild", "sit", "ipsum", "dolor", "NA", "amet", "lorem"];
我希望将其排序为:
["amet", "dolor", "ipsum", "lorem", "sit", "NA", "Wild"];
我在想类似
arr.sort(function(a,b) {
var aVal = a, bVal = b;
// Hack to make values < "NA" < "Wild"
if (aVal == "NA") aVal = "zzz" + aVal;
if (bVal == "NA") bVal = "zzz" + bVal;
if (aVal == "Wild") aVal = "zzzz" + aVal;
if (bVal == "Wild") bVal = "zzzz" + bVal;
return aVal.toLowerCase().localeCompare(bVal.toLowerCase());
});
但这可能不适用于所有Unicode字符。
我也对高性能算法感兴趣!
仅供参考,通过jsPerf ,TJ Crowder的算法性能更高 。 Altohugh我更喜欢Halcyon的更简洁的方法!
您可以在排序功能中添加例外。 通过一点点聪明的数学,我得到了:
arr.sort(function(a,b) {
var exceptions = [ "NA", "Wild" ], indexA, indexB;
indexA = exceptions.indexOf(a);
indexB = exceptions.indexOf(b);
if (indexA === -1 && indexB === -1) {
return a.toLowerCase().localeCompare(b.toLowerCase()); // regular case
}
return indexA - indexB; // index will be -1 (doesn't occur), 0 or 1
});
因此,基本上,所有字符串都小于"Wild"
,并且除"Wild"
以外的所有字符串都小于"NA"
。 传递到该函数sort
应当返回一个负数,如果a < b
0
如果a == b
,或正数,如果a > b
。 因此,您可以通过返回适当的值来处理特殊情况:
arr.sort(function(a,b) {
// Everything is less than "Wild"
if (a === "Wild") {
return 1; // a is greater than b
}
if (b === "Wild") {
return -1; // b is greater than a
}
// Everything else is less than "NA"
if (a === "NA") {
return 1; // a is greater than b
}
if (b === "NA") {
return -1; // b is greater than a
}
// Normal result
return a.toLowerCase().localeCompare(a.toLowerCase());
});
(显然,详细的注释使它看起来比实际的要长...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.