0

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)
RoyBarOn
  • 919
  • 3
  • 24
  • 63
  • Your result will not include objects which have a `user` property that has no keys. Is that on purpose? – trincot Aug 08 '22 at 12:43
  • 1
    Do the checks in `sortUsers` and return a value that sorts them accordingly: [How to sort an array of objects by multiple fields?](https://stackoverflow.com/questions/6913512/how-to-sort-an-array-of-objects-by-multiple-fields) (imho a possible dupe) – Andreas Aug 08 '22 at 12:44
  • @trincot they do have them, in `sortedUsers` object – vanowm Aug 08 '22 at 12:44
  • Use a custom comparison function. If both users don't have hobbies, they're equal. If one has hobbies and the other doesn't, the first come comes first, and vice versa. If both have hobbies, sort by updated date. – deceze Aug 08 '22 at 12:45
  • @vanowm, there they include the objects that have no `user` property, but that's not what I am referring to. – trincot Aug 08 '22 at 12:45
  • If you need list of users with hobby only - this is pretty good solution, however if you just want non-hobby users be at the end of the list, this can be done in one filter and one sort go – vanowm Aug 08 '22 at 12:46
  • @trincot thanks, the array needs to be sorted as it is - without missing out any objects – RoyBarOn Aug 08 '22 at 12:47
  • 1
    https://jsfiddle.net/bnazd73y/ – vanowm Aug 08 '22 at 13:06

0 Answers0