DEV Community

Discussion on: Sorting an array into groups with reduce

Collapse
 
d521bb85 profile image
Vladimir Ivanenko

Hi! Thank you for the article. Please, let me share my point.
I'm not feeling very confident with functional-like practices, because I started applying them not a long ago. But if I got it right, a callback function we pass to .reduce method should be pure and mutating of input arguments it's not a good practice.

I would love to suggest the following implementation:

function groupEmails(addresses) {
  return addresses.reduce(
    (result, addr) => {
      const [name, host] = addr.split('@');
      const value = host in result ? result[host].concat(name) : [name];

      return {
        ...result,
        [host]: value
      };
    },
    {}
  );
}

Thank you. Sorry if I got you wrong.

Collapse
 
jacobmparis profile image
Jacob Paris

The accumulator used in a reduce function is a temporary variable created by the reduce function. The only scope that has access to it is the current iteration of reduce, so creating a new variable each time is unnecessary.

If we were to mutate the addresses argument, we would run into the problems you're hinting at so that indeed is bad practice, but none of those issues exist with the reduce-accumulator.

Collapse
 
nancysavchenko profile image
nancysavchenko

how do you combine [name] with [host] to become email?