DEV Community

Discussion on: Sorting an array into groups with reduce

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

Great article. It’s a great example of how to utilize .reduce but it also reminds me why I’d rather see a helper library like lodash or immutableJS since it’s shorter, more readable, and has already been tested.

But seriously awesome job of proving the value of reduce (especially since it’s basically the cornerstone of functional programming) :)

Collapse
 
jacobmparis profile image
Jacob Paris • Edited

I'm really not sure how lodash or immutable are shorter or more readable. Immutable just has its own wrapper method for its own classes, and Lodash's implementation is almost identical to JS.

// summing with javascript
array.reduce((acc, item) => acc + item, 0);

// summing with lodash
_.reduce(array, (acc, item) => acc + item, 0);

It's better to use the native javascript method because the performance of that will improve over time with improvements to the runtime engines and development of javascript as a whole. Lodash's performance depends on the version of the library you are using at the time.

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.