简体   繁体   English

JavaScript数组对2个属性进行排序

[英]JavaScript array sort on 2 properties

I have a JSON array of objects that looks something like this: 我有一个对象的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
}];

Initially, I needed to sort the array by priority so I did this: 最初,我需要按优先级对数组进行排序,所以我这样做:

garments.sort(function (a, b) {

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

which was fine. 很好 But now, I have realised that if a garment is not designable, then it should be at the bottom of the array regardless of it's priority. 但是现在,我已经意识到,如果一件衣服不可设计,那么无论其优先级如何,它都应该位于阵列的底部。 Can anyone help me with the sort function so all non designable garments are at the bottom of the sort? 谁能帮助我实现分类功能,使所有不可设计的服装都排在最后?

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

Solution with one line of code. 用一行代码解决。

First build the difference between isDesignable and if the same apply the difference of priority as sort indicator. 首先建立isDesignable之间的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>'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM