Beyond String Keys: Grouping Objects with Map.groupBy()

Beyond String Keys: Grouping Objects with Map.groupBy()

Learn how we can use Map.groupBy to group our objects

In a prior blog post, I discussed how to group an array of objects by one of their properties. However, this approach is limited to string keys. To group objects by any type of key, such as an object or number, we can use the Map.groupBy() method.

Map.groupBy()

Map.groupBy method takes 2 arguments first one is the array itself and the second one is the callback function, The syntax of this method looks like Map.groupBy(items, callbackFn)

the callback function takes 2 arguments current element and current index.

Suppose we have an array of objects

 let array = [{ name: "Blackberry", type: "Fruit" },
  { name: "Cantaloupe", type: "Fruit" },
  { name: "Tomato", type: "Vegetable" },
  { name: "Honeydew Melon", type: "Fruit" },
  { name: "Potato", type: "Vegetable" },
  { name: "Watermelon", type: "Fruit" },
  { name: "Carrot", type: "Vegetable" },
  { name: "Onion", type: "Vegetable" }
];

and we want to group them into 2 groups - isFruit and isVegetable but these 2 keys are not strings but objects as shown below.

var isFruit = { fruit:true };
var isVegetable = { fruit:false };
var result = Map.groupBy(array,({type}) => type == "Vegetable" ? 
isVegetable : isFruit 
);
console.log(result);

on running the above code we get the following output

as you can see we get a map as output with 2 entries with keys not as strings but objects.

Whatif we want to group them into 2 groups with 1 representing fruits and 0 representing vegetables, then our code will look something like this

var result = Map.groupBy(array,({type}) => type == "Vegetable" ? 1 : 0);

then the output will look like this

Pitfall

It is supported in all browsers but in Safari as Array.prototype.groupToMap. For more information refer to this

Thanks for reading.