I have array of object:
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] },
];
I want to sort it like this, Sort By name ascending, and then no ascending and then by size1 if it not null.
At first, I can sort it by name and no, but after that I don't know how to sort by size1 or size2. It should sorted by size1 first if it is not null.
Here is my code to sort
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;
}
});
}
Expected result
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] },
]
To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.
You would have to compare no in your first if:
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;
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With