Does anyone enjoy using an Array reduce method? They are weirdly difficult to wrap my head around. If there is an alternative, I’m likely to choose it. However, every once in a while, the Array.reduce() really is the right tool for the job.

There is one specific scenario where I have found it helpful, and that is doing complicated grouping. Suppose we have this data:


const snacks = [
  { snack: "Banana Peel Chips", category: "salty" },
  { snack: "Gummy Worms on a Pretzel Stick", category: "sweet" },
  { snack: "Cheese Puff Castle", category: "salty" },
  { snack: "Jellybean Mosaic", category: "sweet" },
  { snack: "Peanut Butter & Marshmallow Sandwich", category: "salty" },
  { snack: "Marshmallow Tower", category: "sweet" },
  { snack: "Pretzel Necklace", category: "salty" },
  { snack: "Cucumber Caterpillar", category: "salty" },
  { snack: "Chocolate Chip Cookie Pizza", category: "sweet" },
  { snack: "Ice Cream Sandwich", category: "sweet" }
]

We can group by category with:


const grouped = snacks.reduce((all, one) => {
  // if we already have some in this category, keep the list. Otherwise,
  // initialize it
  all[one.category] = all[one.category] || [];

  // add this one to the list
  all[one.category].push(one.snack);

  // don't forget to return all
  return all;
}, {} /* initial value is an empty object*/);

This returns:


{
  "salty": [
    "Banana Peel Chips",
    "Cheese Puff Castle",
    "Peanut Butter & Marshmallow Sandwich",
    "Pretzel Necklace",
    "Cucumber Caterpillar"
  ],
  "sweet": [
    "Gummy Worms on a Pretzel Stick",
    "Jellybean Mosaic",
    "Marshmallow Tower",
    "Chocolate Chip Cookie Pizza",
    "Ice Cream Sandwich"
  ]
}

For more on Array.reduce, and ideas for ways to avoid using reduce, see the Mozilla Developer Network post about Array.reduce