Is there a way to sort an array of objects in JavaScript that contains null and undefined values? The goal is to display items with a "jobTitle" property first, sorted by rating, followed by items without a "jobTitle" also sorted by rating. Sample 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'}
]
Once the data is sorted by jobTitle and then by rating, it should look like this:
[
{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 attempted various methods such as:
data.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
However, these approaches did not handle undefined and null values properly. I'm looking for a solution that does not involve creating new arrays or merging data, ideally completing the task within a single method.
EDIT
The desired outcome is to first list items with jobTitles sorted by their ratings AND then list those without jobTitles, also sorted by rating.