Sorting array in javascript by boolean, surname and name

Viewed 167

I try to sort my array of objects :

object:

interface IFriend {
  _id: string;
  name: string;
  surname: string;
  avatar: string;
  online: boolean;
}

I want to do it in order - online, surname, name. I tried this :

  friendsCopy
    .sort((a: IFriend, b: IFriend) =>
      a.online === b.online ? 0 : a.online ? -1 : 1
    )
    .sort((a: IFriend, b: IFriend) => a.surname.localeCompare(b.surname, "pl"))
    .sort((a: IFriend, b: IFriend) => a.name.localeCompare(b.name, "pl"));

But it doesn't work well

2 Answers

Because you are sorting in the wrong direction.

If you reverse the functions then it should give your desired output:

friendsCopy
    .sort((a: IFriend, b: IFriend) => a.name.localeCompare(b.name, "pl"))
    .sort((a: IFriend, b: IFriend) => a.surname.localeCompare(b.surname, "pl"))
    .sort((a: IFriend, b: IFriend) =>
      a.online === b.online ? 0 : a.online ? -1 : 1
    );

Sort by name, then sort by surnames, then sort by who is online. The final list will be online -> surname -> name

As mentioned in the other answer, you are sorting in the reverse direction. The final sort is prioritized over the others.

You can club them all to a single sort using the || operator.

friendsCopy.sort((a, b) => b.online - a.online 
                || a.surname.localeCompare(b.surname, "pl") 
                || a.name.localeCompare(b.name, "pl")
    )

First, sort the array by online property. You can simply subtract the booleans since they get coerced to numbers and result in -1, 0 or 1 based on their value.

true - false === 1
false - true === -1
true - true === 0
false - false === 0

All the online: true objects will be moved to the front of the array. If both the objects being compared have the same online value, then the subtraction returns 0 and the || operator moves to the next condition and sorts them based on surname. Again, if the objects have the same surname property, then finally the objects are sorted based on name property.

Related