DEV Community

Discussion on: Sorting an array into groups with reduce

Collapse
 
cubiclebuddha profile image
Cubicle Buddha • Edited

Forgive me for not being more clear in my first comment. I didn't mean that you should replace native .reduce with lodash's .reduce. I meant that .groupBy is a drop in replacement for your custom reduce.

const sortedEmails = _.groupBy(emails, anEmail => {
    const emailProvider = anEmail.split('@')[1];
    return emailProvider;
})

That's 3 lines instead of 8 and (to me) it's more scan-able/readable since I see "groupBy" and I immediately know that we're categorizing by email provider.

Btw, I often use native .reduce. But when I can reach out to a method name that more clearly communicates my goals, then I do that since it's more in line with self-documenting code. Again, those are just my opinions. What are your thoughts?

Thread Thread
 
jacobmparis profile image
Jacob Paris

Oh yes -- I understand now.

I'm a strong believer in refactoring code for reusability, so if I needed to group more arrays by one of their fields I would absolutely adopt a specialized and well-named function that does that. In this case, Lodash is a perfectly acceptable alternative.