简体   繁体   中英

Javascript sort array on property array

So I have this array of users that looks something like this:

[{
    userName: 'Jim',
    roles: ['Member']
}, {
    userName: 'Adam',
    roles: ['Administrator']
}, {
    userName: 'Suzy',
    roles: ['SuperUser']
}, {
    userName: 'Greg',
    roles: ['SuperUser']
}, {
    userName: 'Ady',
    roles: ['Administrator']
}, {
    userName: 'Jeremy',
    roles: ['Administrator']
}]

I would like to sort this array by it's roles. I tried doing this:

items.sort(function (a, b) {
    var aValue = a.roles[0];
    var bValue = b.roles[0];

    if (aValue < bValue) return -1;
    if (aValue > bValue) return -1;
    return 0;
});

But it doesn't do what I expect. Does anyone know how to solve this issue?

You can use localeCompare method for string comparison inside sort() .

 var data = [{"userName":"Jim","roles":["Member"]},{"userName":"Adam","roles":["Administrator"]},{"userName":"Suzy","roles":["SuperUser"]},{"userName":"Greg","roles":["SuperUser"]},{"userName":"Ady","roles":["Administrator"]},{"userName":"Jeremy","roles":["Administrator"]}] data.sort(function(a, b) { return a.roles[0].localeCompare(b.roles[0]) }) console.log(data) 

give this a shot

function SortByRole(a, b){
  var aRole = a.roles[0];
  var bRole = b.roles[0]; 
  return ((aRole < bRole) ? -1 : ((aRole > bRole) ? 1 : 0));
}

array.sort(SortByRole);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM