In my Angular project, I developed a custom pipe that allows for grouping an array of objects based on a specific property:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'groupBy'})
export class GroupByPipe implements PipeTransform {
transform(value: Array<any>, field: string): Array<any> {
const groupedObj = value.reduce((prev, cur)=> {
if(!prev[cur[field]]) {
prev[cur[field]] = [cur];
} else {
prev[cur[field]].push(cur);
}
return prev;
}, {});
return Object.keys(groupedObj).map(key => ({ key:key, value: groupedObj[key] }));
}
}
<div>
<h2>Group by department</h2>
<ul>
<li *ngFor="let group of employees | groupBy:'department'">Department{{group.key}}
<ul>
<li *ngFor="let event of group.value">
{{event.firstName}} {{event.lastName}}
</li>
</ul>
</li>
</ul>
The implementation above works flawlessly!
However, now I am looking to tackle a different challenge.
In the example within the app.component: https://stackblitz.com/edit/angular-rc3njv
I have an array of strings:
email = ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60020c0120070d01090c4e030f0d">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbacacac8baca6aaa2a7e5a8a4a6">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c1bbbbbb81a6aca0a8adefa2aeac">[email protected]</a>","<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef828282af87809b828e8683c18c8082">[email protected]</a>"]
and I aim to group this array based on substring. For instance: @gmail.com forms one group with emails like "[email protected]", "[email protected]", "[email protected]"; @hotmail is another group containing "[email protected]"
Does anyone have insights on how to customize the existing pipe in the provided example so it can effectively group an array of strings based on substrings?
Appreciate any help!