Dennis J
Dennis J

Reputation: 186

How to Sort associative array by one property value still maintaining alphabetical order (another property value)?

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

Answers (1)

Esailija
Esailija

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

Related Questions