Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Juni4567/b54416111f1efe497e78a29c5cae3326 to your computer and use it in GitHub Desktop.
Save Juni4567/b54416111f1efe497e78a29c5cae3326 to your computer and use it in GitHub Desktop.
How to sort emails array with JavaScript based on given importance object as number
function emailSort(a, b) {
const importance = {"gmail.com": 1, "yahoo.com": 2, "rocketmail.com": 3, "ymail.com": 4};
const importanceOfA = importance[a.split('@')[1]];
const importanceOfB = importance[b.split('@')[1]];
if (importanceOfA && !importanceOfB) return -1;
if (importanceOfB && !importanceOfA) return 1;
if (importanceOfA && importanceOfB) return importanceOfA - importanceOfB;
return 0;
}
arra = [
"juni1@rocketmail.com",
"juni2@rocketmail.com",
"juni3@rocketmail.com",
"juni1@yahoo.com",
"juni2@yahoo.com",
"juni3@yahoo.com",
"juni1@ymail.com",
"juni3@ymail.com",
"juni2@ymail.com",
"juni1@gmail.com",
"junaid4567@gmail.com",
"juni4@gmail.com",
]
newArray = arra.sort(emailSort);
console.log(newArray)
//will return
// [ 'juni4@gmail.com', 
// 'junaid4567@gmail.com', 
// 'juni1@gmail.com', 
// 'juni1@yahoo.com', 
// 'juni2@yahoo.com', 
// 'juni3@yahoo.com', 
// 'juni2@rocketmail.com', 
// 'juni3@rocketmail.com', 
// 'juni1@rocketmail.com', 
// 'juni2@ymail.com', 
// 'juni3@ymail.com', 
// 'juni1@ymail.com' ] 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment