我有像这样的json数据
[ { groupType: '1',
id: '158',
unreadMessages: '8',
ownerId: '332',
name: 'porras group' },
{ groupType: '1',
id: '163',
unreadMessages: '0',
ownerId: '337',
name: '11..' },
{ groupType: '1',
id: '173',
unreadMessages: '0',
ownerId: '334',
name: 'cate\'s' },
{ groupType: '1',
id: '174',
unreadMessages: '0',
ownerId: '328',
name: 'raju' },
{ groupType: '1',
id: '175',
unreadMessages: '0',
ownerId: '332',
name: 'abcde' },
{ groupType: '1',
id: '177',
unreadMessages: '0',
ownerId: '337',
name: '26 feb' },
{ groupType: '1',
id: '181',
unreadMessages: '0',
ownerId: '332',
name: 'new' },
{ groupType: '1',
id: '182',
unreadMessages: '0',
ownerId: '337',
name: 'jchhabra group' },
{ groupType: '1',
id: '186',
unreadMessages: '0',
ownerId: '337',
name: 'jch' },
{ groupType: '1',
id: '189',
unreadMessages: '0',
ownerId: '332',
name: 'hebe' },
{ groupType: '1',
id: '191',
unreadMessages: '0',
ownerId: '328',
name: 'ccgg' },
{ groupType: '1',
id: '202',
unreadMessages: '0',
ownerId: '332',
name: 'New Porras Group' },
{ groupType: '1',
id: '205',
unreadMessages: '0',
ownerId: '339',
name: 'simgroup' },
{ groupType: '1',
id: '210',
unreadMessages: '0',
ownerId: '339',
name: 'check' },
{ groupType: '1',
id: '222',
unreadMessages: '1',
ownerId: '333',
name: 'jgonzalez group' },
{ groupType: '1',
id: '223',
unreadMessages: '0',
ownerId: '334',
name: 'Cate 2' },
{ groupType: '2',
id: '150',
unreadMessages: '0',
ownerId: '0',
name: 'BACKSTAFF Group 2' },
{ groupType: '2',
id: '158',
unreadMessages: '0',
ownerId: '0',
name: 'BACKSTAFF Group' },
{ groupType: '2',
id: '173',
unreadMessages: '0',
ownerId: '0',
name: 'BACKSTAFF Group 3' } ]
我希望排序
这样就可以在json列表中进行排序了 数字首先是大写字母与字母和休息 按字母顺序。
答案 0 :(得分:1)
假设您假装直接在代码中订购(而不是像数据库那样在数据源中),您可以编写一些简单的代码来执行此操作。
首先让我们从基本比较功能开始
function compareString(a, b) {
if ( !(a && b) ) return Math.sign(a.length - b.length);
const ca = a.codePointAt(0);
const cb = b.codePointAt(0);
const cmp = Math.sign(ca - cb);
return cmp ? cmp : compareString(a.slice(1), b.slice(1));
}
构建基本排序功能后,您可以对任何对象进行排序。以您的对象数组为例:
const groups = //your groups here;
const sorted = groups.sort( (a, b) => compareString(a.name, b.name));
我使用了一些ES6语法,如果您有任何问题,请与我们联系。
编辑:我现在开车(不开车),我稍后会解释完整的代码。EDIT2:使用上面的代码获得此订单(仅限组名)
[ '11..',
'26 feb',
'BACKSTAFF Group',
'BACKSTAFF Group 2',
'BACKSTAFF Group 3',
'Cate 2',
'New Porras Group',
'abcde',
'cate\'s',
'ccgg',
'check',
'hebe',
'jch',
'jchhabra group',
'jgonzalez group',
'new',
'porras group',
'raju',
'simgroup' ]
EDIT3:在停车时,我已经顿悟了,并意识到你想要的是javascript的默认字符串排序。我非常专注于你的问题,我完全忘记了我在做什么。无论如何,我会将上面的代码作为参考。但是您可以使用此代码对数组进行排序
const sorted = groups.sort( (a, b) => a.name > b.name ? 1 : -1 )
它有多简单?基本上它使用与上面代码相同的策略,只是比较字符串的ASCII代码。查看table以检查函数的排序优先级。
尽管
,UTF8替代品对可能会变得令人讨厌