JavaScript数组排序2个属性

时间:2015-10-07 12:28:44

标签: javascript arrays

我有一个JSON数组对象,看起来像这样:

var garments [{
    name: 'Garment 1',
    isDesignable: false,
    priority: 3
},{
    name: 'Garment 2',
    isDesignable: false,
    priority: 1
},{
    name: 'Garment 3',
    isDesignable: true,
    priority: 3
},{
    name: 'Garment 4',
    isDesignable: true,
    priority: 2
},{
    name: 'Garment 5',
    isDesignable: true,
    priority: 4
}];

最初,我需要按优先级对数组进行排序,所以我这样做了:

garments.sort(function (a, b) {

    // By priority
    return a.priority - b.priority;
});

这很好。但是现在,我已经意识到,如果服装不可设计,那么它应该位于数组的底部,而不管它的优先级如何。任何人都可以帮我解决排序功能,所以所有不可设计的服装都在排序的底部吗?

2 个答案:

答案 0 :(得分:4)

garments.sort(function (a, b) {
    if (a.isDesignable == b.isDesignable) {
        return a.priority - b.priority;
    } else if (a.isDesignable) {
        return -1;
    } else {
        return 1;
    }
});

答案 1 :(得分:1)

使用一行代码解决方案。

首先构建isDesignable之间的差异,如果相同则将priority的差异应用为排序指标。

var garments = [{
        name: 'Garment 1',
        isDesignable: false,
        priority: 3
    }, {
        name: 'Garment 2',
        isDesignable: false,
        priority: 1
    }, {
        name: 'Garment 3',
        isDesignable: true,
        priority: 3
    }, {
        name: 'Garment 4',
        isDesignable: true,
        priority: 2
    }, {
        name: 'Garment 5',
        isDesignable: true,
        priority: 4
    }];
// sort isDesignable first and then by priority ascending
garments.sort(function (a, b) {
    return b.isDesignable - a.isDesignable || a.priority - b.priority;
});
document.write('<pre>' + JSON.stringify(garments, 0, 4) + '</pre>');

// sort reversing the former sort order by sorting, not reversing
garments.sort(function (a, b) {
    return a.isDesignable - b.isDesignable || b.priority - a.priority;
});
document.write('<pre>' + JSON.stringify(garments, 0, 4) + '</pre>');