Search code examples
javascriptarraysjsontypescriptmultidimensional-array

Convert an array of object into 2-dimensional array to group the elements with same id in typescript


I have an array of object as

arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2 name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];

I want to convert the above array to 2-d array based on catid of the element(basically want to group all elements on the basis of same catid):

arr2 = [[{catid: 1, name: 'mango', category: 'fruit'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'} ],[{catid: 2 name: 'potato', category: 'veg'}],[{catid: 3, name: 'chiken', category: 'nonveg'}]]

How can I do this in typescript or javascript.


Solution

  • You can do it with Object.groupBy():

    const arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2, name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];
    
    const result = Object.values(Object.groupBy(arr1, item => item.catid));
    console.log(JSON.stringify(result));

    You could also use Array#reduce():

    Playground

    const arr1 = [{catid: 1, name: 'mango', category: 'fruit'}, {catid: 2, name: 'potato', category: 'veg'}, {catid: 3, name: 'chiken', category: 'nonveg'},{catid: 1, name: 'apple', category: 'fruit'}, {catid: 1, name: 'banana', category: 'fruit'}];
    
    const result = arr1.reduce((r, item) => 
        ((r.map.get(item.catid)?.push(item) ?? r.map.set(item.catid, r.arr[r.arr.length] = [])), r), 
        {map: new Map<typeof arr1[number]['catid'], typeof arr1[number][]>, arr: new Array<typeof arr1>}).arr;
    
    console.log(JSON.stringify(result));