我正在使用ag-grid-react来显示来自端点的数据表。我有一个列,其中包含字母数字值,需要使用“自然”排序算法进行排序(即数字分组在一起,字母数字字符串分组在一起……)
下面是我的专栏定义。在网格上启用排序,当我单击列对网格进行排序时,除了一些以数字开头中断以C开头的字符串序列的字符串外,所有内容都已排序。
这种情况发生在ag网格的默认排序算法中,无论accentedSort是真是假,甚至是使用基本的自定义排序比较器(见下文)。
列定义:
field: 'cqttUnitPayItemDescriptionId',
headerName: 'Description',
type: 'dropdown',
editable: true,
resizable: true,
valueGetter: (p) => {
const value = p.data[p.colDef.field];
const cellDescription = p.data.description;
// returns a string value for display
// `items` is an ImmutableJs Map of objects, grouped by index, containing a `description` string property.
return value >= 0 ? items.getIn([value, 'description']) || cellDescription : value;
},
cellEditorFramework: AgGridCellEditor({ component: AgDropdownEditor, renderProps: innerProps => ({ createable: true, labelProperty: 'description', options: itemsByUnitPayItemId.getIn([innerProps.data.unitPayItemId], Map()).toList(), ...innerProps }) }),
sortable: true,
width: 250,
comparator: StringComparator
},自定义排序比较器:
export function StringComparator(valueA: string = '', valueB: string = '') {
const valueALower = valueA.toLowerCase();
const valueBLower = valueB.toLowerCase();
return valueALower.localeCompare(valueBLower, 'en', { numeric: true });
}排序不一致的可视化示例:

给出上面的截图:对比较器的手动测试表明字符串"4‘x8’x16‘(拖线Mat)“应该出现在”string“移动之前--领带”(即用这些参数调用比较器的返回值是-1),但是网格显然不这么认为。我是不是遗漏了对比较器函数的调用范围?
发布于 2019-08-17 01:24:04
结果发现,一些正在排序的字符串在字符串的开头就包含了一个空格,导致它们(正确地)在数字和字母字符之前进行排序。通过简单地将.trim()附加到StringComparator中比较的每个值的末尾,我解决了这个问题
export function StringComparator(valueA: string = '', valueB: string = '') {
const valueALower = valueA.toLowerCase().trim();
const valueBLower = valueB.toLowerCase().trim();
return valueALower.localeCompare(valueBLower, 'en', { numeric: true });
}https://stackoverflow.com/questions/57528061
复制相似问题