Search code examples
rxjsreactive-programming

Reactive JS (RxJs) Group by key


I have a data stream with e.g. the following values:

Observable.of(
    [{time: 1000, a: 100},
    {time: 1000, b: 100},
    {time: 2000, a: 200}]
);

And need to merge the values based on time to get:

[{time: 1000, a: 100, b: 100},
{time: 2000, a: 200}]

I can use map and reduce but then I end up with a single map that I have to split somehow again. Is there a more straight forward way in RxJs?


Solution

  • You could just do an array reduce inside of a map operator. Might be a bit clearer than the groupBy and flatMap. This is more of a data mapping issue than an rxjs issue.

    Rx.Observable.of(
    	[{time: 1000, a: 100},
       {time: 1000, b: 100},
       {time: 2000, a: 200}]
    ).map(data => {
      return data.reduce((acc, cur) => {
        const index = acc.findIndex(x => x.time === cur.time);
        if (index >= 0) {
          acc[index] = { ...acc[index], ...cur };
        } else {
          acc.push(cur);
        }
        return acc;
      }, [])
    })
    .subscribe(x => { console.log('result', x); });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.7/Rx.min.js"></script>