1

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?

1

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)
    );
  }),
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.