user16691768
user16691768

Reputation: 113

How to sort an array of string per priority?

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?

Upvotes: 1

Views: 2561

Answers (2)

Talmacel Marian Silviu
Talmacel Marian Silviu

Reputation: 1736

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

Upvotes: 0

Spectric
Spectric

Reputation: 31987

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)

Upvotes: 7

Related Questions