Skip to content
Advertisement

Sort the array so that zero values are at the bottom of each group and the remaining values are sorted alphabetically

It is necessary to sort the array so that values with the same currentUser are on top and these values are sorted by name, if there is no name, then it is necessary to sort them down each group.

const currentUser = 256;
const settings = [
  {
    name: null,
    userId: 256,
  },
  {
    name: 'Bear',
    userId: 256,
  },
  {
    name: 'Anatomy',
    userId: 256,
  },
  {
    name: null,
    userId: 12,
  },
  {
    name: null,
    userId: 23,
  },
  {
    name: 'Anatomy',
    userId: 43,
  },
];

settings.sort((a, b) => {
  const aName = a.name || null;
  const bName = b.name || null;

  return (
    (aName === null) - (bName === null) ||
    Number(b.userId === currentUser) - Number(a.userId === currentUser) ||
    aName - bName
  );
});

console.log(settings);

The result should be an array:

[
  {
    name: 'Anatomy',
    userId: 256,
  },
  {
    name: 'Bear',
    userId: 256,
  },
  {
    name: null,
    userId: 256,
  },
  {
    name: 'Anatomy',
    userId: 43,
  },
  {
    name: null,
    userId: 12,
  },
  {
    name: null,
    userId: 23,
  },
]

I would appreciate any help, best regards, have a nice day.

Advertisement

Answer

Following is the ordering followed in the code:

  • Give highest preference to userId‘s matching currentUser and if two userId‘s match currentUser, then sort them alphabetically by their name and for null names put them at the last (in that group).
  • Sort other items by their userId in descending order.
  • For items that have same userId, again sort them alphabetically by their name and for null names put them at the last (in that group).

const currentUser = 43;
const settings = [
  { name: null, userId: 256 },
  { name: null, userId: 43 },
  { name: "Abby", userId: 43 },
  { name: "Bear", userId: 256 },
  { name: "John", userId: 256 },
  { name: "Simon", userId: 43 },
  { name: null, userId: 12 },
  { name: null, userId: 23 },
  { name: "Anatomy", userId: 43 },
];

function sortByName(a, b) {
  if (Object.is(a, null) && Object.is(b, null)) {
    return 0;
  } else if (Object.is(a, null)) {
    return 1;
  } else if (Object.is(b, null)) {
    return -1;
  } else {
    return a.localeCompare(b);
  }
}

settings.sort((a, b) => {
  // Objects that have same `userId` as `currentUser`
  if (a.userId === currentUser && b.userId === currentUser) {
    return sortByName(a.name, b.name);
  } else if (a.userId === currentUser) {
    return -1;
  } else if (b.userId === currentUser) {
    return 1;
  }

  // Other objects
  if (a.userId > b.userId) {
    return -1;
  } else if (a.userId < b.userId) {
    return 1;
  } else {
    return sortByName(a.name, b.name);
  }
});

console.log(settings);
Advertisement