0

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?

1
  • 2
    You're returning -1 for two comparison cases. One should return 1, depending on your sort order (ascending or descending) Commented Jun 8, 2017 at 17:16

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.