I'm trying to sort my javascript array of objects
ownerName dogCode dogName
Bob 5 Rex
John
Alisha 3 Moon
Darren 4 Boss
Josh
Cerq
I want it to be sort first by dogCode (just if exists or not, ignoring the number), than by ownerName, and finally by dogName, like this:
ownerName dogCode dogName
Alisha 3 Moon
Bob 5 Rex
Darren 4 Boss
Cerq
John
Josh
I tried this:
data.sort(function (a, b) {
if (a.dogCode < b.dogCode || !a.dogCode) return 1;
if (a.dogCode > b.dogCode || !b.dogCode) return -1;
if (a.ownerName < b.ownerName || !a.ownerName) return 1;
if (a.ownerName > b.ownerName || !b.ownerName) return -1;
if (a.dogName < b.dogName || !a.dogName) return 1;
if (a.dogName > b.dogName || !b.dogName) return -1;
return 0;
});
Aparenttely, It is sorting by dogCode correctly, but not by name/dogName. How can I do this?
EDIT: here is my json object:
{
"data": [
{
"ownerName": "Bob",
"dogCode": "5",
"dogName": "Rex"
},
{
"ownerName": "John"
},
{
"ownerName": "Alisha",
"dogCode": "3",
"dogName": "Moon"
},
{
"ownerName": "Darren",
"dogCode": "4",
"dogName": "Bos"
},
{
"ownerName": "Josh"
},
{
"ownerName": "Cerq"
}
]
}
dogCode? do you have some data for testing?