Is there a way to efficiently organize an array like the following in cases where certain fields are missing?
For instance, consider the current array:
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'
}
]
The desired result should follow this order of sorting:
- An object containing both
firstname
andlastname
- An object with only
firstname
orlastname
- An object without either
firstname
orlastname
Resulting in the sorted array looking like this:
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
}
]
Attempts at sorting have been made, but the outcome is not as intended.
users.sort((a,b) => {
if (a.firstname === b.firstname) {
return 0
}
if (!a.firstname) {
return 1
}
return -1
});