array.groupBy in TypeScript

后端 未结 4 1495
囚心锁ツ
囚心锁ツ 2021-02-19 19:01

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

4条回答
  •  别跟我提以往
    2021-02-19 19:06

    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)=>{
                        [...]
                    })
    

提交回复
热议问题