How can I sort an object array which has null and undefined values using javascript. My target is to show items that has property of "jobTitle" first, order them by rating, then items with no "jobTitle" ordered by rating again. Data:
data = [
{name: 'John', rating: null},
{name: 'Ethel', rating: 1.34, jobTitle: 'engineer'},
{name: 'Abba', rating: 5.44},
{name: 'Harry', rating: 0.44, jobTitle: 'plumber'}
]
After data is sorted by jobTitle and then by rating it should be like:
[
{name: 'Ethel', rating: 1.34, jobTitle: 'engineer'},
{name: 'Harry', rating: 0.44, jobTitle: 'plumber'},
{name: 'Abba', rating: 5.44},
{name: 'John', rating: null}
]
I have tried many variations like:
data.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
but it did not work for undefined and null values. I do not want to use low quality solutions like creating new arrays, fill with data and merge them. I want to achieve that in single method if possible.
EDIT
In general response should show first those who has jobTitle orderd by rating AND then those who don't have jobTitle ALSO ordered by rating.