Search code examples
angularsortingobservable

Sorted Observable based on another Observable - Angular


I have an Observable anmed "History" in which there is an array of elements. It is represented by this json file : (As you can see there are 3 types of entries just the id changes...)

I would like to create another Observable in which I store each type of entry sorted by the number of times they are present in the json file. With the json file that is above.

How do I go through my "History" Observable and create a sorted "Content" Observable based on the number of times there is each entry in the "History" Observable


Solution

  • Assuming two entries are the same based on the SNS.

    First you need to count all the entries, then you can place them in sorted order.

    Here is an implementation where original$ is the original observable.

      new$ = original$.pipe(map((res: any) => this.sort(res.history)));
    
      sort(history: any[]): any[] {
        const result = [];
        const counts: { [key: string]: number } = {};
        for (const i of history) {
          if (counts[i.SNS] === undefined) {
            counts[i.SNS] = 0;
            result.push(this.stripId(i));
          }
          counts[i.SNS]++;
        }
        return result.sort((a, b) => counts[b.SNS] - counts[a.SNS]);
      }
    
      stripId(object: any) {
        const result = { ...object };
        delete result.id;
        return result;
      }
    

    I use any because I'm too lazy to create types for this example, but you should use actual types.

    Stackblitz: https://stackblitz.com/edit/angular-ivy-rqzyx8?file=src/app/app.component.ts