Javascript – 如何通过3种不同的属性类型对对象数组进行排序? (String,Integer,Boolean)

我有一个对象数组:

var a = [
  {"name": "BBB", "no": 2, "size1": [3], "size2": null },
  {"name": "AAA", "no": 5, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 1, "size1": [2], "size2": null },
  {"name": "AAA", "no": 4, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 1, "size1": null, "size2": [1] },
  {"name": "AAA", "no": 5, "size1": [2], "size2": null },
  {"name": "BBB", "no": 2, "size1": null, "size2": [1] },
];

我想按照这样排序,按名称升序排序,然后不升序,然后按size1,如果它不为空.

起初,我可以按名称排序,不可以,但之后我不知道如何按size1或size2排序.如果它不为null,它应该首先按size1排序.
这是我要排序的代码

function sortObject(arrayObjects){
    arrayObjects.sort(function(a,b){
        if(a.name=== b.name){
            return (a.no - b.no);
        } else if(a.name > b.name){
            return 1;
        } else if(a.name < b.name){
            return -1;
        }
    });
}

预期结果

var a = [
  {"name": "AAA", "no": 4, "size1": null, "size2": [1] },
  {"name": "AAA", "no": 5, "size1": [2], "size2": null },
  {"name": "AAA", "no": 5, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 1, "size1": [2], "size2": null },
  {"name": "BBB", "no": 1, "size1": null, "size2": [1] },
  {"name": "BBB", "no": 2, "size1": [3], "size2": null },
  {"name": "BBB", "no": 2, "size1": null, "size2": [1] },
]
最佳答案
你必须在第一个中比较否:

function sortObject(arrayObjects){
    arrayObjects.sort(function(a,b){
        if (a.name=== b.name) {
            if (a.no === b.no) {
                // Determines which size to use for comparison
                const aSize = a.size1 || a.size2;
                const bSize = b.size1 || b.size2;

                return (aSize[0] - bSize[0]);
            }
            return (a.no - b.no);
        } else if (a.name > b.name) {
            return 1;
        } else if (a.name < b.name) {
            return -1;
        }
    });
}

转载注明原文:Javascript – 如何通过3种不同的属性类型对对象数组进行排序? (String,Integer,Boolean) - 代码日志