break array of objects into separate arrays based on a property

后端 未结 7 1164
太阳男子
太阳男子 2020-12-01 07:10

Say I have an array like this:

var arr = [
    {type:\"orange\", title:\"First\"},
    {type:\"orange\", title:\"Second\"},
    {type:\"banana\", title:\"Thi         


        
7条回答
  •  离开以前
    2020-12-01 07:47

    Typescript version.

    /**
    * Group object array by property
     * Example, groupBy(array, ( x: Props ) => x.id );
     * @param array
     * @param property
     */
    export const groupBy = (array: Array, property: (x: T) => string): { [key: string]: Array } =>
      array.reduce((memo: { [key: string]: Array }, x: T) => {
        if (!memo[property(x)]) {
          memo[property(x)] = [];
        }
        memo[property(x)].push(x);
        return memo;
      }, {});
    
    export default groupBy;
    

提交回复
热议问题