array.groupBy in TypeScript

后端 未结 4 1876
盖世英雄少女心
盖世英雄少女心 2021-02-19 18:50

The basic array class has .map, .forEach, .filter, and .reduce, but .groupBy i noticably absent, preventing me f

4条回答
  •  Happy的楠姐
    2021-02-19 19:14

    you could add the function to the array prototype in your app (note some don't recomend this: Why is extending native objects a bad practice?):

    Array.prototype.groupBy = function(/* params here */) { 
       let array = this; 
       let result;
       /* do more stuff here*/
       return result;
    }; 
    

    Then create an interface in typescript like this:

    .d.ts version:

        interface Array
        {
            groupBy(func:(x:T) => string): Group[]
        }
    

    OR in a normal ts file:

    declare global {
       interface Array
       {
          groupBy(func:(x:T) => string): Group[]
       }
    }
    

    Then you can use:

     props.tags.groupBy((t)=>t.category_name)
         .map((group)=>{
                        [...]
                    })
    

提交回复
热议问题