How can I sort a javascript array of objects numerically and then alphabetically? [duplicate]

I think it’s better done just with…

items.sort(function(a, b) { 
  return a.id - b.id  ||  a.name.localeCompare(b.name);
});

The second sort will basically negate the first one, so you have to do it once. )

a.id - b.id || a.name.localeCompare(b.name) expression will first compare the ids; only if they are equal, it will compare the names (and return the result of this comparison).

If you need to reverse the ordering, swap the positions (b.id - a.id, etc.) – or just negate the whole thing:

items.sort(function(a, b) { 
  return - ( a.id - b.id  ||  a.name.localeCompare(b.name) );
});

Here’s the JSFiddle (have to simplify the data a bit to show my point).

Leave a Comment