Search code examples
angularautocompleterxjsrxjs-observables

GroupBy an RxJS Observable into key-values


I have the following entries with the type Observable<User[]>:

[{
   "id": 1,
   "name": "Testuser 1",
   "projectAccess": Role,
}] 

.json

Role {
id: string;
name:string;
}

so requirement is like to have an array where user is group-by role which i want to pass inside generic autocomplete component as group-entries

  return data:
  [{
  manager, [{"1", "Frank"}, {"3", "Seba"}]
  },
  {employee, [{"2", "Simi"}]
  },]

any help will be appreciated.Thank You


Solution

  • In order to achieve groupby functionality you have to implement your own groupby function.

    The function has no difference between using with observables and simple arrays due to the pipe(map()) combination

    In order to achive this question is quite similar to this question The algorithm listed there results in an object where the keys of the object is the groupped property and the values are the occurancies in the list.

    Example code

    private testUser:Observable<User[]>

    this.testuser.pipe(map((value)=>{
       return groupBy(value);
    }))
    
    
    
    groupBy(user[]) {
      let groupped=xs.reduce(function(rv, x) {
        (rv[x.ProjectAccess.Name] = rv[x.ProjectAccess.Name] || []).push(x);
        return rv;
      }, {});
    
      let returnList=[];
    
      for(let i in groupped){
       returnList.push({role:i,value:groupped[i]})
      }
    };