JavaScript array sort on 2 properties

后端 未结 2 1080
误落风尘
误落风尘 2021-01-29 11:18

I have a JSON array of objects that looks something like this:

var garments [{
    name: \'Garment 1\',
    isDesignable: false,
    priority: 3
},{
    name: \'         


        
相关标签:
2条回答
  • 2021-01-29 11:53

    Solution with one line of code.

    First build the difference between isDesignable and if the same apply the difference of priority as sort indicator.

    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>');

    0 讨论(0)
  • 2021-01-29 12:04
    garments.sort(function (a, b) {
        if (a.isDesignable == b.isDesignable) {
            return a.priority - b.priority;
        } else if (a.isDesignable) {
            return -1;
        } else {
            return 1;
        }
    });
    
    0 讨论(0)
提交回复
热议问题