Saturday, 12 November 2016

jquery - How can I sort a javascript array of objects numerically and then alphabetically?











How can I sort an array of objects numerically (by id) then alphabetically (by name)?



The current way is providing invalid output.



This is the object i'm trying to sort through



var items = [

{
"id": 165,
"name": "a"
},
{
"id": 236,
"name": "c"
},
{
"id": 376,

"name": "b"
},
{
"id": 253,
"name": "f"
},
{
"id": 235,
"name": "e"
},

{
"id": 24,
"name": "d"
},
{
"id": 26,
"name": "d"
}
]



and the way i'm trying to sort



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



here is the jsfiddle.



http://jsfiddle.net/jh4xb/



EDIT: Sorry for the confusion, I've been so confused by this problem for a while.



What I'm trying to accomplish is to sort by the highest id first, and then sort alphabetically so in the end it should look like:



var items = [
{

"id": 376,
"name": "b"
},
{
"id": 253,
"name": "f"
},
{
"id": 236,
"name": "c"

},
{
"id": 235,
"name": "e"
},
{
"id": 165,
"name": "a"
},
{

"id": 26,
"name": "d"
},
{
"id": 24,
"name": "d"
}
]

Answer




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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...