skip to Main Content

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.

2

Answers


  1. 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));
    
    Login or Signup to reply.
  2. As an alternative, a for loop can be used;

          // Group arrays by 'catid'
            const arr1 = [
                {catid: 1, name: 'mango', category: 'fruit'},
                {catid: 2, name: 'potato', category: 'veg'},
                {catid: 3, name: 'chicken', category: 'nonveg'},
                {catid: 1, name: 'apple', category: 'fruit'},
                {catid: 1, name: 'banana', category: 'fruit'}
            ];
    
            const result = {};
    
            for(var {catid, name, category} of arr1) {
                if(!result[catid]) result[catid] = [];
                result[catid].push({ catid, name, category });
            }
    
            console.log(JSON.stringify({"Data": result},null,2));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search