Sorting an array into groups with reduce
Jacob Paris
Posted on May 3, 2019
I help run the discord server Devcord and spend much of my time helping novice programmers with technical difficulties. Starting now, I'll be formalizing any help I give there into short blog posts here so the information isn't buried under a sea of conversations.
Here I had a user with a list of email addresses to be sorted by domain.
const emails = [
"alice@gmail.com"
"bob@gmail.com"
"carol@yahoo.ca"
"doug@hotmail.com"
"ellie@protonmail.com"
];
While there are many ways to tackle this problem, my preferred is the functional model using Array.prototype.reduce
const sortedEmails = emails.reduce((groups, email) => {
const splitString = email.split('@');
const account = splitString[0];
const domain = splitString[1];
if(!groups[domain]) groups[domain] = [];
groups[domain].push(account);
return groups;
}, {});
The reduce function iterates each element of the array and passes the return object to the next iteration. The accumulator
(named groups
here) is set initially as a {}
empty object.
For each email, we break it into variables for each the account and the domain. If our current domain isn't already one of our groups, initialize it as an empty array.
Then add the new account name to the group and return groups
to pass it into the next iteration.
{
"gmail.com": ["alice", "bob"],
"yahoo.ca": ["carol"],
"hotmail.com": ["doug"],
"protonmail.com": ["ellie"]
}
It should be noted that this code isn't completely suitable for production environments. While almost every email address has only one @
symbol and this will work for all of those, there are valid email addresses that have multiple. Parsing the entire specification of valid email addresses is outside the scope of this article.
Posted on May 3, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.