Issue
I believe that I am looking for an Angular pipe that will allow for me to group items in an array together based on and defined key from the array. As an example, if I had an array with these state
and country keys
:
items: any = [
{
"state": "Illinois",
"country": "USA"
},
{
"state": "Florida",
"country": "USA"
},
{
"state": "Ontario",
"country": "Canada"
}
];
As I would iterate through my list, i'd like for the pipe to group the items with the same key together in a list so that when it is displayed to the user they could see like items together.
Do I need to create a custom pipe for this or just filter the items a particular way, or is there a way to accomplish this using a map
in rxjs
or a filter
?
Solution
I'm unsure which guidelines this post didn't follow, but here was my solution after a number of attempts:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'groupBy'
})
export class GroupByPipe implements PipeTransform {
transform(collection: any[], property: string): any[] {
// prevents the application from breaking if the array of objects doesn't exist yet
if(!collection) {
return null;
}
const groupedCollection = collection.reduce((previous, current) => {
if (!previous[current[property]]) {
previous[current[property]] = [current];
} else {
previous[current[property]].push(current);
}
return previous;
}, {});
// this will return an array of objects, each object containing a group of objects
return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));
}
}
Now it my templates I can use the pipe to group items together:
<div *ngFor="let category of categories | groupBy: 'category'">
<h3>{{ category.key }}</h3>
<ul>
<li *ngFor="let item of category.value">{{ item.title }}</li>
</ul>
</div>
Answered By - zeropsi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.