我有对象数组:
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] },
];
我想这样排序,按 name
升序排序,然后按 no
升序排序,如果不为 null,则按 size1 排序。
起初,我可以按name
和no
排序,但之后我不知道如何按size1
或大小 2
。如果它不为空,它应该首先按 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] },
]
最佳答案
您必须在第一个 if
中比较 no
:
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 种不同的属性类型对对象数组进行排序? (字符串、整数、 bool 值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52113626/