I need to sort an array, by users that has hobbies and updated lately - but some of the users are not active (the object only has the user id) - and since they don't have the 'hobbies' key - i can't do a simple sorting.... so i came up with the following solution - but i think there is a better one.
const users = [
{
"id": "1",
"user": {
"name": "Ben",
"hobbies": {
"reading": "1",
"music": "1",
"pets": "0"
},
"updated": "Mon Aug 08 2022 15:24:23 GMT+0300 (Israel Daylight Time)"
}
},
{
"id": "2",
"user": {
"name": "John",
"hobbies": {},
"updated": "Mon Aug 08 2022 13:24:23 GMT+0300 (Israel Daylight Time)"
}
},
{
"id": "3"
},
{
"id": "4",
"user": {
"name": "Ren",
"hobbies": {
"reading": "0",
"music": "1",
"pets": "0"
},
"updated": "Mon Aug 08 2022 12:24:23 GMT+0300 (Israel Daylight Time)"
}
}
]
function sortUsers(a,b){
return new Date(b.user.updated) > new Date(a.user.updated) ? 1 : -1;
}
const nonActiveUsers = users.filter(i => !i.user);
const activeUsersWithHobbies = users.filter(i => i.user && Object.keys(i.user.hobbies).length).sort(sortUsers);
const sortedUsers = [...activeUsersWithHobbies, ...nonActiveUsers];
console.log(activeUsersWithHobbies)