先按照color排好序,再按照size进行排序
var d = [{"color": "red", "size": "1"},{"color": "red", "size": "2"},{"color": "blue", "size": "3"},{"color": "blue", "size": "2"},{"color": "blue", "size": "1"}];
var sortTwoCate=function(a,b){
if (a["color"] === b["color"]) {
if (a["size"] > b["size"]) {
return 1;
} else if (a["size"] < b["size"]) {
return - 1;
} else {
return 0;
}
} else {
if (a["color"] > b["color"]) {
return 1;
} else {
return - 1;
}
}
}
d.sort(sortTwoCate);
console.log(JSON.stringify(d));
输出内容:
[{"color":"blue","size":"1"},{"color":"blue","size":"2"},{"color":"blue","size":"3"},{"color":"red","size":"1"},{"color":"red","size":"2"}]