Reputation: 129
Good day, i've been trying to display an array by groups title, i get my array from a webservice and i want to display the item by groups title
example
Group1 item 1 item 2 item 3
Group2 item 1 item 2 item 3
here is my array
[
{
"id": "1",
"title": "Item 1",
"groups": [
{
"id": "2",
"title": "Communication"
}
]
},
{
"id": "2",
"title": "Item 2",
"groups": [
{
"id": "2",
"title": "Communication"
}
]
},
{
"id": "3",
"title": "Item 1",
"groups": [
{
"id": "1",
"title": "Creativie Art"
}
]
},
{
"id": "4",
"title": "Item 3",
"groups": [
{
"id": "2",
"title": "Communication"
}
]
},
{
"id": "5",
"title": "Item 2",
"groups": [
{
"id": "1",
"title": "Creativie Art"
}
]
},
{
"id": "6",
"title": "Item 3",
"groups": [
{
"id": "1",
"title": "Creativie Art"
}
]
}
]
i cant paste all the array data because its too long but this is the array structure
Upvotes: 0
Views: 3971
Reputation: 214027
Here is one option of how we can do it:
app.component.ts
const groupsDict = this.arr.reduce((acc, cur) => {
cur.groups.forEach(({ id, title}) => {
acc[id] = acc[id] || { id, title };
acc[id].items = acc[id].items || [];
acc[id].items.push({ id: cur.id, title: cur.title });
});
return acc;
}, {});
this.groups = Object.keys(groupsDict).map(x => groupsDict[x]);
app.component.html
<div class="grid">
<div *ngFor="let group of groups" class="col">
<h2>{{ group.title }}</h2>
<div *ngFor="let item of group.items">
{{ item.title }}
</div>
</div>
</div>
Upvotes: 6