我有一个数据将显示为表格,并使用orderBy(lodash)对数据进行排序,但它不能按我的要求工作。
现在,我编码为
const data = orderBy(realData, ['name'], ['asc'])
这是我的数据
输入:
[{name: 'A1'},{name:'A2'},{name: 'A21'},{name:'B10'},{name: 'A100'},{name:'A22'},{name: 'B32'},{name:'A3'}]
问题是“ orderBy”对文本进行排序(ASCII排序)
当前输出:
[{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}]
但是我想要这样的数据输出
[{name: 'A1'},{name:'A2'},{name:'A3'},{name: 'A21'},{name:'A22'},{name: 'A100'},{name:'B10'},{name: 'B32'}]
如果有人有任何建议,请帮助。
谢谢。
答案 0 :(得分:2)
在对数组进行排序时,可以使用string#localeCompare
回调。要对数组进行数字排序,请使用numeric
属性。
let data = [{name: 'A1'},{name: 'A100'},{name:'A2'},{name: 'A21'},{name:'A22'},{name:'A3'},{name:'B10'},{name: 'B32'}];
data.sort((a,b) => a.name.localeCompare(b.name, undefined, {numeric: true}));
console.log(data);
.as-console-wrapper {max-height: 100% !important; top: 0;}
答案 1 :(得分:0)
一种易于理解的方式是这样的:
data.sort((a, b) => {
const listA = a.name.trim().split('');
const listB = b.name.trim().split('');
const categoryA = listA.splice(0, 1);
const categoryB = listB.splice(0, 1);
const numberA = listA.join('');
const numberB = listB.join('');
if (categoryA > categoryB) return 1;
if (categoryA < categoryB) return -1;
return numberA - numberB;
});