2

I have the following method that returns result as shown below:

result: [ { status: 200, ... }, { status: 200, ... }, { status: 400, ... }, ... ]
    

I need to group the result by using status value and return only 2 results instead of 3 for the example result above:

update() {
  this.demoService.update(...).toPromise()
  .then(result => {

    const message = result.map((x: any) => {
      if (x.status === 200) {
        return {
          text: 'successful'
        };
      } else {
        return {
          text: 'fail'
        };
      }
    });

    }
  })
}

I tried to use groupBy of RxJs but I think it cannot be used in Promise. So, how can I group this result in the example above?

  • Why do you even use a `Promise`? You can use `groupBy()` when piping the observable: `this.demoService.update(...).pipe(groupBy())` – DonJuwe Feb 16 '21 at 10:01
  • Yes, but I am wondering if there is a possibility to use groupBy in toPromise? –  Feb 16 '21 at 10:03
  • You cannot use RxJs Operators there. But you can achieve it with normal mapping: https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects – DonJuwe Feb 16 '21 at 10:06
  • `groupBy` is a `RxJs` operator and can be used only inside `pipe()`: https://www.learnrxjs.io/learn-rxjs/operators/transformation/groupby. Do you need to print only distinct status codes? – AlleXyS Feb 16 '21 at 10:12
  • @DonJuwe Which one do you mean in that example? could you please post the one you refer to the update method in my question and post as answer? –  Feb 16 '21 at 10:12

2 Answers2

1

I'm not sure it works, but you can try (you filter only entities with distinct status, then select only statuses):

update() {
  this.demoService.update(...).subscribe(result => {
    const messages = result
        .filter((x, i, arr) => arr.findIndex(t => t.status === x.status) === i)
        .map(x => x.status);

    // do stuff
  });
}
AlleXyS
  • 2,476
  • 2
  • 17
  • 37
1

Create a custom grouping method like this:

var groupBy = (xs, key) => {
  return xs.reduce((rv, x) => {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};

console.log(groupBy([{status: 200, foo: 'bar'}, {status: 200, foo: 'baz'}, {status: 400, foo: 'bar'}], 'status'));

Output:

{
    "200": [
        {
            "status": 200,
            "foo": "bar"
        },
        {
            "status": 200,
            "foo": "baz"
        }
    ],
    "400": [
        {
            "status": 400,
            "foo": "bar"
        }
    ]
}
DonJuwe
  • 4,477
  • 3
  • 34
  • 59