Home > OS >  How to sort an array of string per priority?
How to sort an array of string per priority?

Time:10-01

I'd like to ask how could I sort an array of string per priority email domain?

For example, this is my priority list

1st: gmail.com
2nd: outlook.com
3rd: yahoo.com
4th: hotmail.com
5th: live.com
6th: Other Domain

So, if this is my string

const personalEmail = ['[email protected]','[email protected]','[email protected]','[email protected]','[email protected]']

What are ways to achieve this?

Please don't downvote. I really need help. Thank you.

CodePudding user response:

You can store the order of the domains in an array, then in the sort callback, subtract the two domain's index in the array to determine precedence.

If one of the indexes is -1, sort the other item before the one whose domain wasn't in the array.

const domainPrecedence = ['gmail.com', 'outlook.com', 'yahoo.com', 'hotmail.com', 'live.com']

const personalEmail = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']


const sorted = personalEmail.sort((a, b) => {
  let index1 = domainPrecedence.indexOf(a.split('@')[1])
  let index2 = domainPrecedence.indexOf(b.split('@')[1])
  return index1 == -1 ? 1 : index2 == -1 ? -1 : index1 - index2;
})

console.log(sorted)

CodePudding user response:

This is assuming that other.com means it could by any other domain.

const priority = [
  'gmail.com',
  'outlook.com',
  'yahoo.com',
  'hotmail.com',
  'live.com',
];

const personalEmail = [

  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
  '[email protected]',
];

console.log(
  personalEmail.sort((a, b) => {
    const firstIndex = priority.indexOf(a.split('@')[1]);
    const secondIndex = priority.indexOf(b.split('@')[1]);
    return (
      (firstIndex === -1 ? 5 : firstIndex) -
      (secondIndex === -1 ? 5 : secondIndex)
    );
  }),
);

  • Related