我需要对包含字母/数字/和前导零的字符串数组进行排序。 如果为 null,则必须转到列表顶部并显示为空字符串。我已经查看并研究了许多不同的方法,但没有一种方式符合我的期望。
初始数组:
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' },
]
预期输出:
- " ">
- " ">
- "-">
- "0">
- "0001">
- 《001》
- "01">
- "01.008">
- "01.008A">
- "1">
- "02">
- "2">
- "10">
- "10-1">
- "100">
- "100A1">
- "A">
- "A1">
编辑:(我的原始代码(
function sortAlphanumeric<T>(this: Array<T>, property: string): Array<T> {
var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
if (sortOrder == -1) {
return b[property].localeCompare(a[property]);
} else {
return a[property].localeCompare(b[property]);
}
}
}
return this.sort(dynamicSort(property)).sort((a, b) => {
var nullToEmptyString = '';
if (a[property] === null) {
a[property] = nullToEmptyString;
}
if (b[property] === null) {
b[property] = nullToEmptyString;
}
return 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 || "")