How to Group Data and Find Maximums by Group in Angular using RxJS
How to Group Data and Find Maximums by Group in Angular using RxJS
Have you ever faced an interview question where you need to take a flat list of employee records and group them by department to find the highest earner?
While it sounds straightforward, doing this reactively with RxJS can quickly lead to tricky bugs if operators are chained out of order. In this post, we will look at a common broken snippet, dissect why it fails, and implement two clean ways to solve it.
The Problem Scenario
Imagine you have the following flat dataset inside an Angular component:
The goal is to calculate the maximum salary department-wise and output a clean structure like this:
✅ Solution 1: The Correct RxJS Reactive Stream
To do this properly using RxJS, you must manipulate the data inside the inner group pipeline before sending it back to the main stream.
⚡ Solution 2: The High-Performance Native JavaScript Way (Pro-Tip)
If an interviewer asks you this question, a fantastic way to stand out is to offer architectural nuance.
Ask yourself: Do we actually need RxJS streams here?
Since
Since
this.employees is already a local, synchronous synchronous array, using an RxJS pipeline adds overhead. You can compute this much faster using standard array .reduce():Why mention this in an interview?
- Time Complexity: It iterates over the array exactly once, running in O(N) time.
- Readability: It avoids complex RxJS imports and sub-pipelines.
- Pragmatism: It proves you know when not to use a library when native features are cleaner.
Summary Checklist for RxJS Grouping
- Creation methods like
from()live in'rxjs'. - Pipeable operators like
groupBy,mergeMap, andtoArraylive in'rxjs/operators'. - Always use
mergeMap()right aftergroupBy()to handle the inner streams individually. - Remember to import
JsonPipeinto your Angular component'simportsarray if you want to test output via{{ data | json }}!
Comments
Post a Comment