Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

What are ways to achieve this?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!