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@yahoo.com','email@live.com','email@other.com','email@gmail.com','email@outlook.com']

What are ways to achieve this?

E_net4
  • 27,810
  • 13
  • 101
  • 139
user16691768
  • 93
  • 1
  • 8
  • Does this answer your question? [Javascript - sort array based on another array](https://stackoverflow.com/questions/13304543/javascript-sort-array-based-on-another-array) also [Most efficient way to get the string with highest priority out of an array](https://stackoverflow.com/questions/45574811/most-efficient-way-to-get-the-string-with-highest-priority-out-of-an-array) or [Ordering an array of strings according to a specific arrangement of strings](https://stackoverflow.com/questions/59740589/ordering-an-array-of-strings-according-to-a-specific-arrangement-of-strings) – pilchard Sep 30 '21 at 22:50

2 Answers2

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@yahoo.com', 'email@live.com', 'email@other.com', 'email@gmail.com', 'email@outlook.com']


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)
Spectric
  • 30,714
  • 6
  • 20
  • 43
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@yahoo.com',
  'email@live.com',
  'lasvegas@baby.com',
  'email@other.com',
  'email@gmail.com',
  'email@outlook.com',
];

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)
    );
  }),
);
Talmacel Marian Silviu
  • 1,596
  • 2
  • 6
  • 14