我正在寻找对由数字和文本及其组合组成的数组进行排序的最简单方法。
例如,
'123asd'
'19asd'
'12345asd'
'asd123'
'asd12'
变成了
'19asd'
'123asd'
'12345asd'
'asd12'
'asd123'
这将与 another question I've asked here 的解决方案结合使用.
排序函数本身是有效的,我需要的是一个可以说“19asd”小于“123asd”的函数。
我正在用 JavaScript 编写此内容。
我正在寻找一个自然排序的函数。
最佳答案
现在可以在现代浏览器中使用 localeCompare 来实现这一点。通过传递 numeric: true
选项,它将智能地识别数字。您可以使用 sensitivity: 'base'
不区分大小写。它在 Chrome、Firefox 和 Internet Explorer 11 中进行了测试.
这是一个例子。它返回 1
,意味着 10 在 2 之后:
'10'.localeCompare('2', undefined, {numeric: true, sensitivity: 'base'})
为了提高对大量字符串进行排序时的性能,the article说:
When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property.
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['1_Document', '11_Document', '2_Document'];
console.log(myArray.sort(collator.compare));
关于javascript - JavaScript 中字母数字字符串的自然排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28577241/