0

如何按“组”值对对象进行排序/分组,同时仍保持字母顺序(“名称”值)?

例如之前

    [{
        name:'A'
        group:'a',
    },
    {
        name:'A'
        group:'b',
    },
    {
        name:'B'
        group:'a',
    },
    {
        name:'B'
        group:'b'
    }]

    [{
        name:'A'
        group:'a',
    },
    {
        name:'B'
        group:'a',
    },
    {
        name:'A'
        group:'b',
    },
    {
        name:'B'
        group:'b'
    }]
4

1 回答 1

1

检查组是否相等,如果是,则比较名称。如果组不相等,则比较组。

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*/
});
于 2012-08-07T10:36:46.610 回答