Angular custom pipe to remove duplicates in an array of objects

Viewed 342

I am iterating over a custom object using *ngFor to populate the select dropdown. The object name is herdCountSummary. It contains a string variable herdCountSummary.usageperiod which has values in the form "QTR 1, 2020". Examples of values it contains are below:

QTR 1, 2020
QTR 2, 2020
QTR 3, 2020
QTR 4, 2020
QTR 1, 2019
QTR 2, 2019
QTR 1, 2018

My requirement is to get the year part and populate it in the year dropdown and there is another dropdown for quarter part. Quarter dropdown must be dependent on the year dropdown. So if the user selects 2019 in the year, only QTR 1, and QTR 2 values should be available to be selected in the quarter dropdown.

I was able to separate the year and quarter part but was not able to remove the duplicates and make the quarter dropdown dependent on year.

So I was thinking to write a custom pipe and call that pipe from html like this.

<option *ngFor="let item of herdCountSummary | distinctPipe" value={{item.usagePeriod}}>
   {{item.usagePeriod}}
</option>

Can anyone please let me know how can I write the pipe. I have tried enough but I am new to Angular and typescript.

1 Answers

I was able to complete this by creating the separate pipes for both year and quarter dropdowns. I used the filter operator to remove the duplicates from the year dropdown. So now I have got distinct years in the year dropdown. And once the user selects a particular year, I am sending the selected year value to the quarter pipe and matches the year present, if it matches, the quarter part is separated using split() function and will be pushed to an array and that array is returned.

Related