Back to Freecodecamp

Challenge 80: Email Sorter

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/68e39ed6106dac2f0a98fd62.md

latest2.7 KB
Original Source

--description--

On October 29, 1971, the first email ever was sent, introducing the username@domain format we still use. Now, there are billions of email addresses.

In this challenge, you are given a list of email addresses and need to sort them alphabetically by domain name first (the part after the @), and username second (the part before the @).

  • Sorting should be case-insensitive.
  • If more than one email has the same domain, sort them by their username.
  • Return an array of the sorted addresses.
  • Returned addresses should retain their original case.

For example, given ["[email protected]", "[email protected]", "[email protected]"], return ["[email protected]", "[email protected]", "[email protected]"].

--hints--

sort(["[email protected]", "[email protected]", "[email protected]"]) should return ["[email protected]", "[email protected]", "[email protected]"].

sort(["[email protected]", "[email protected]", "[email protected]"]) should return ["[email protected]", "[email protected]", "[email protected]"].

sort(["[email protected]", "[email protected]", "[email protected]"]) should return ["[email protected]", "[email protected]", "[email protected]"].

sort(["[email protected]", "[email protected]", "[email protected]"]) should return ["[email protected]", "[email protected]", "[email protected]"].

sort(["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"]) should return ["[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]"].

--seed--

--seed-contents--

js
function sort(emails) {

  return emails;
}

--solutions--

js
function sort(emails) {
  return emails.slice().sort((a, b) => {
    const [userA, domainA] = a.split('@');
    const [userB, domainB] = b.split('@');

    const domainCompare = domainA.toLowerCase().localeCompare(domainB.toLowerCase());
    if (domainCompare !== 0) return domainCompare;

    return userA.toLowerCase().localeCompare(userB.toLowerCase());
  });
}