Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • 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 = [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]
newArray = arra.sort(emailSort);
console.log(newArray)
//will return
// [ '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]', 
// '[email protected]' ] 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment