How can I sort array something like below if any of fields is missing?
So existing array for example is:
const users = [
{
id: 1, firstname: 'Jerry'
}, {
id: 2, firstname: 'Thomas', lastname: 'Geib'
}, {
id: 3
}, {
id: 4, lastname: 'Berg'
}, {
id: 5, firstname: 'Ass', lastname: 'Noob'
}, {
id: 6, lastname: 'Jopa'
}
]
and the result should be sorted in this order:
- Object with
firstnameandlastname - Object only with
firstnameorlastname - Object without
firstnameandlastname
so that it would look like:
const users = [
{
id: 2, firstname: 'Thomas', lastname: 'Geib'
}, {
id: 5, firstname: 'Ass', lastname: 'Noob'
}, {
id: 1, firstname: 'Jerry'
}, {
id: 4, lastname: 'Berg'
}, {
id: 6, lastname: 'Jopa'
}, {
id: 3
}
]
I've tried this sorting but result is not that I needed
users.sort((a,b) => {
if (a.firstname === b.firstname) {
return 0
}
if (!a.firstname) {
return 1
}
return -1
});
firstnameandlastname?