Reputation: 186
How do I sort/group the objects by the "group" values while still maintaining an alphabetical order ("name" value)?
E.g. Before
[{
name:'A'
group:'a',
},
{
name:'A'
group:'b',
},
{
name:'B'
group:'a',
},
{
name:'B'
group:'b'
}]
After
[{
name:'A'
group:'a',
},
{
name:'B'
group:'a',
},
{
name:'A'
group:'b',
},
{
name:'B'
group:'b'
}]
Upvotes: 0
Views: 188
Reputation: 140220
Check if the groups are equal, if so, compare names. If the groups are not equal, compare groups.
var a = [{
name: 'A',
group: 'a'
}, {
name: 'A',
group: 'b'
}, {
name: 'B',
group: 'a'
}, {
name: 'B',
group: 'b'
}]
a.sort(function(a, b) {
return a.group.localeCompare(b.group) === 0 ?
a.name.localeCompare(b.name) : /*groups are equal, compare names*/
a.group.localeCompare(b.group); /* groups are not equal, compare groups*/
});
Upvotes: 1