This is my data:
[{
"id": 1,
"name": "item 1",
"group": "Group A"
}, {
"id": 2,
"name": "item 2",
"group": "Group A"
}, {
"id": 3,
"name": "item 3",
"group": "Group B"
}, {
"id": 4,
"name": "item 4",
"group": "Group B"
}, {
"id": 5,
"name": "item 5",
"group": "Group B"
}, {
"id": 6,
"name": "item 6",
"group": "Group C"
}]
And I want to create table like this:
|======================|
|ID |NAME |
|======================|
|Group A |
|----------------------|
|1 |item 1 |
|2 |item 2 |
|======================|
|Group B |
|----------------------|
|3 |item 3 |
|4 |item 4 |
|5 |item 5 |
|======================|
|Group C |
|----------------------|
|6 |item 6 |
========================
I tried create variable to store "group" in each loop but not work and I can group at server side before return data, I still want do it at client, so how to do that ?
You can use below logic for achieving your result.
var groups = new Set(array.map(item => item.group)),
results = [];
groups.forEach(g =>
results.push({
name: g,
values: array.filter(i => i.group === g)
}
))
HTML
<div *ngFor="let item in results">
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<ng-container>
<tr>
<td colspan="2">{{item.name}}</th>
</tr>
<tr *ngFor="let value in item.values">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
</tr>
</ng-container>
</table>
<div>
Working Stackblitz
You can use reduce()
and filter
method to create your array as group by with group name.
I have created a demo in stackblitz. Hope this will help/guide you to achieve your requirement.
CODE SNIPPET
.ts file code
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
array = [
{
"id": 1,
"name": "item 1",
"group": "Group A"
},
{
"id": 2,
"name": "item 2",
"group": "Group A"
},
{
"id": 3,
"name": "item 3",
"group": "Group B"
},
{
"id": 4,
"name": "item 4",
"group": "Group B"
},
{
"id": 5,
"name": "item 5",
"group": "Group B"
},
{
"id": 6,
"name": "item 6",
"group": "Group C"
}
];
groupArr = this.array.reduce((r,{group})=>{
if(!r.some(o=>o.group==group)){
r.push({group,groupItem:this.array.filter(v=>v.group==group)});
}
return r;
},[]);
}
template
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tbody *ngFor="let item of groupArr">
<ng-container>
<tr >
<td colspan="2"><b>{{item.group}}</b></td>
</tr>
<tr *ngFor="let value of item.groupItem">
<td>{{value.id}}</td>
<td>{{value.name}}</td>
</tr>
</ng-container></tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With