I need a way to prevent showing duplicated content in angular template. I have an array of data, and some of those data share the same formId. In my template I am showing the name of the array, and if the formId is unique, then after there is a divider line, but if the array share the same formId the divider line is not shown until the formId is changed. So If I have the array:
[
{
id: 1,
name: 'Test 1'
formId: '8979f9879f'
},
{
id: 2,
name: 'Test 2'
formId: '8979f9879f'
},
{
id: 3,
name: 'Test 3'
formId: 'a8098981'
},
]
The result should be:
Test 1
Test 2
_______
Test 3 ... and so on
The ones that share the same formId, I need to put in the same table layout, so I needed to group the data with same formId, getting the result like this:
[
8979f9879f: [
{
id: 1,
name: Test 1,
formId: 8979f9879f
},
{
id: 2,
name: Test 2,
formId: 8979f9879f
},
],
a8098981: [
{
id: 3,
name: Test 3,
formId: a8098981
}
]
]
Which is fine. But now in a template when I loop though this arrays:
<ng-container *ngFor="let formItem of formListItems | async, index as i">
<div *ngFor="let groupedItem of groupedFormListItems[formItem.formId]" ...
I get the correct layout and result, only I get the duplicated result, because nested loop. So the layout on the page looks like this:
Test 1 Test 2
Test 1 Test 2
Test 3
I need somehow to check if the formId is already been looped through, but don't know how to do that.
CodePudding user response:
You need a better manipulation of the array, so that you can group same formId test together, but also keep them easily accessible via ngFor
. Here's a quick and dirty solution.
CodePudding user response:
you can use "reduce" to group elements
this.processFormData=this.formList.reduce((a:any,b:any)=>{
const element=a.find(x=>x.formId==b.formId)
if (element)
element.items.push(b)
else
a.push({formId:b.formId,items:[b]})
return a;
},[])
NOTE: The reduce return an array, has no sense return an abject if you want iterate over this