Home > database >  Grouping array of objects to object of arrays by multiple keys and adding the id's of the group
Grouping array of objects to object of arrays by multiple keys and adding the id's of the group

Time:01-05

Made sample of code -

Interface -

interface IInterface {
  id: number;
  name: string;
  age: number;
}

array -

const arr: IInterface[] = [
    {
        id: 1,
        name: 'daniel',
        age: 12
    },
    {
        id: 2,
        name: 'jonny',
        age: 13
    },
    {
        id: 3,
        name: 'daniel',
        age: 12
    },
    {
        id: 4,
        name: 'daniel',
        age: 12
    }
]

GroupBy function -

const GroupBy = (
  array: IInterface[],
  f: (element: IInterface) => (string | number | undefined)[]
) => {
  const groups: { [key: string]: IInterface[] } = {};

  array.forEach((object) => {
    const group = f(object).join("-");

    groups[group] = groups[group] || [];
    groups[group].push(object);
  });
  return groups;
};

Using the groupBy function -

const Grouped = GroupBy(arr, (element: IInterface) => {
        return [
          element.name, element.age,
        ];
      });

Result now -

{
  "daniel-12": [
    {
      "id": 1,
      "name": "daniel",
      "age": 12
    },
    {
      "id": 3,
      "name": "daniel",
      "age": 12
    },
    {
      "id": 4,
      "name": "daniel",
      "age": 12
    }
  ],
  "jonny-13": [
    {
      "id": 2,
      "name": "jonny",
      "age": 13
    }
  ]
}

Wanted result -

{
  "daniel-12-ids-1-3-4": [
    {
      "id": 1,
      "name": "daniel",
      "age": 12
    },
    {
      "id": 3,
      "name": "daniel",
      "age": 12
    },
    {
      "id": 4,
      "name": "daniel",
      "age": 12
    }
  ],
  "jonny-13-ids-2": [
    {
      "id": 2,
      "name": "jonny",
      "age": 13
    }
  ]
} 

Need that all the group id's will by at the key name .......................................................................................................................................................

CodePudding user response:

You could create a new object from the old one.

const
    grouped = { "daniel-12": [{ id: 1, name: "daniel", age: 12 }, { id: 3, name: "daniel", age: 12 }, { id: 4, name: "daniel", age: 12 }], "jonny-13": [{ id: 2, name: "jonny", age: 13 }] },
    result = Object.fromEntries(Object.entries(grouped).map(([k, v]) => [
        [k, 'ids', v.map(({ id }) => id).join('-')].join('-'),
        v
    ]));

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

  •  Tags:  
  • Related