字母数字/自然排序Javascript中带前导零的数组
我需要对包含字母/数字/和前导零的字符串数组进行排序。 如果为null,则它必须位于列表顶部并显示为空字符串。我已经研究过很多不同的方法,但没有一种方法能达到我所期望的效果 初始数组:字母数字/自然排序Javascript中带前导零的数组,javascript,sorting,alphanumeric,natural-sort,Javascript,Sorting,Alphanumeric,Natural Sort,我需要对包含字母/数字/和前导零的字符串数组进行排序。 如果为null,则它必须位于列表顶部并显示为空字符串。我已经研究过很多不同的方法,但没有一种方法能达到我所期望的效果 初始数组: input = [ { value: null }, { value: '' }, { value: '-' }, { value: '0' }, { value: 'A1' }, { value: '0001' }, { value: '01' },
input = [
{ value: null },
{ value: '' },
{ value: '-' },
{ value: '0' },
{ value: 'A1' },
{ value: '0001' },
{ value: '01' },
{ value: '1' },
{ value: '01.008A' },
{ value: '01.008' },
{ value: '02' },
{ value: 'A' },
{ value: '10' },
{ value: '100A1' },
{ value: '10-1' },
{ value: '100' },
{ value: '001' },
{ value: '2' },
]
预期产出:
函数sortAlphanumeric(this:Array,property:string):数组{
var collator=new Intl.collator(未定义,{numeric:true,敏感度:'base'});
函数dynamicSort(属性){
var-sortOrder=1;
如果(属性[0]=“-”){
sortOrder=-1;
property=property.substr(1);
}
返回函数(a,b){
如果(排序器==-1){
返回b[property].localeCompare(a[property]);
}否则{
返回a[property].localeCompare(b[property]);
}
}
}
返回此.sort(dynamicSort(property)).sort((a,b)=>{
var nullToEmptyString='';
if(a[属性]==null){
a[属性]=nullToEmptyString;
}
if(b[属性]==null){
b[属性]=nullToEmptyString;
}
返回collator.compare(a[property],b[property]);
});
}
这应该可以做到:
input.sort(({value:a}, {value:b}) => {
const ai = parseInt(a, 10), bi = parseInt(b, 10);
return (b == null) - (a == null)
|| (ai - bi)
|| (a > b) - (b > a);
}).map(x => x.value || "")
中的任何方法都不起作用?您需要添加
null
的替换项,如'
。然后重复的tartget工作。并显示为空字符串,这不是排序,这是映射。抱歉第一次在这里发布。我在原始代码中进行了编辑。为什么不在排序之前映射数组?此外,对于字符串比较,@ TeMUs,localeCompare
,因为某些语言环境下的比较是相当不可预测的,我重视简单的标准字符串比较。这是一个了不起的解决方案。这让我头疼。
input.sort(({value:a}, {value:b}) => {
const ai = parseInt(a, 10), bi = parseInt(b, 10);
return (b == null) - (a == null)
|| (ai - bi)
|| (a > b) - (b > a);
}).map(x => x.value || "")