'Using JavaScript need to group elements

I am looking for efficient method to modify my object list which looks something like this:

const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];

So I want to modify my list to get the output like this:

Const Pets = [
    {
      "type": "Dog",
      "name": ["Spot", "Rover"]
    },
    {
      "type": "Cat",
      "name": ["Tiger", "Leo"]
    }
  ];

What I tried:

function groupBy(list, keyGetter) {
  const map = new Map();
  list.forEach((item) => {
    const key = keyGetter(item);
    if (!map.has(key)) {
      map.set(key, [item]);
    } else {
      map.get(key).push(item);
    }
  });
  return map;
}

const pets = [{  type: "Dog",  name: "Spot"}, {  type: "Cat",  name: "Tiger"}, {  type: "Dog",  name: "Rover"}, {  type: "Cat",  name: "Leo"}];

const grouped = groupBy(pets, pet => pet.type);
console.log(grouped);


Solution 1:[1]

An alternative is using the function reduce to group the types and the function Object.values to extract the grouped types.

const pets = [    {type:"Dog", name:"Spot"},    {type:"Cat", name:"Tiger"},    {type:"Dog", name:"Rover"},     {type:"Cat", name:"Leo"}],
      result = Object.values(pets.reduce((a, {type, name}) => {
        (a[type] || (a[type] = {type, name: []})).name.push(name);
        return a;
      }, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Solution 2:[2]

You can use reduce to achieve this as below

var pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];

pets = Object.values(pets.reduce((obj, {type, name}) =>
                (
                    obj[type] = obj[type] || ({type: type, name: [] })
                    , obj[type].name.push(name)
                    , obj
                )
                , {}))
                
                
console.log(pets)

Solution 3:[3]

function groupBy(list, keyGetter) {
    const map = new Map();
    list.forEach((item) => {
        const key = keyGetter(item);
        const collection = map.get(key);
        if (!collection) {
            map.set(key, [item]);
        } else {
            collection.push(item);
        }
    });
    return map;
}
const pets = [] //sample array

const grouped = groupBy(pets, pet => pet.type);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ele
Solution 2 Nitish Narang
Solution 3 Mohi