我有如下所示的数组,我想以更快的方式通过升序或降序对其进行字母数字排序。
[ “NFO:BANKNIFTY1931428900CE” “NFO:BANKNIFTY1931429000CE” “NFO:BANKNIFTY1931429500CE” …
简单地使用 .sort() 。
.sort()
var items = [ "NFO:BANKNIFTY1931428900CE", "NFO:BANKNIFTY1931429000CE", "NFO:BANKNIFTY1931429500CE", "NFO:BANKNIFTY1931429400CE", "NFO:BANKNIFTY1931429300CE", "NFO:BANKNIFTY1931429200CE" ] var sorted = items.sort() console.log(sorted);
通过字母数字方式使用排序数组 localeCompare 方法。
localeCompare
该 的 localeCompare() 强> method返回一个数字,指示引用字符串是在排序顺序之前还是之后出现,或者与排序顺序中的给定字符串相同。
const sortAlphaNum = (a, b) => a.localeCompare(b, 'en', { numeric: true }) console.log([ "NFO:BANKNIFTY1931428900CE", "NFO:BANKNIFTY1931429000CE", "NFO:BANKNIFTY1931429500CE", "NFO:BANKNIFTY1931429400CE", "NFO:BANKNIFTY1931429300CE", "NFO:BANKNIFTY1931429200CE" ].sort(sortAlphaNum))