问题
I have an array with a lot of values looking like this :
I'm trying to sort the array by grouping every "part" that have the same part_image
value and then render the image the value is linked to only 1 single time.
I tried using the groupBy function but without success, does anyone have an approach for this ?
Array variable : selectedDiam
Component.ts
ngOnChanges() {
this.filterDrop();
console.log(this.selectedDiam, ' SELECTED DIAM');
}
filterDrop() {
this.dataDiam1 = this.dataDynParts;
let dynDiam1 = this.dataDiam1.map(obj => obj.diam[0]);
dynDiam1 = dynDiam1.filter((v, i) => dynDiam1.indexOf(v) === i);
this.dataDiam1 = dynDiam1;
this.dataDiam2 = this.dataDynParts;
let dynDiam2 = this.dataDiam2.map(obj => obj.diam[1]);
dynDiam2 = dynDiam2.filter((v, i) => dynDiam2.indexOf(v) === i);
this.dataDiam2 = dynDiam2;
this.createForm();
this.filteredWithDiam = this.dataDynParts;
this.selectedDiam = this.dataDynParts;
this.quotationIdNumber = this.quotationId;
}
Component.html
<div class="products">
<div class="d-flex flex-row linesColor ml-2" *ngFor="let products of selectedDiam; let i = index;">
<a class="flex1">HERE IS WHERE THE PHOTO SHOULD BE RENDERED</a>
<a class="flex1">{{products.l3_label}}</a>
<a class="flex1">{{products.diam[0]}}</a>
<a class="flex1">{{products.diam[1]}}</a>
<a class="flex1">
<input class="number" ngModel="{{products.longueur}}" (ngModelChange)="postQuotationDatas($event,products,'longueur')" type="number">
</a>
<input class="mb-1 flex1 checkbox" ngModel="{{products.hasValve}}" (ngModelChange)="postQuotationDatas($event,products,'hasValve')" type="checkbox">
<a class="flex1 mb-1">
<input class="number" ngModel="{{products.quantity}}" (ngModelChange)="postQuotationDatas($event,products,'quantity')" type="number">
</a>
<a class="flex1">
{{(products.total_fourniture)}}
</a>
</div>
</div>
回答1:
Consider the following snippet:
// assume arr refers to your array of data
const groups = {}; // for storing groups while processing
arr.forEach(v => {
if(groups[v.part_image])
groups [v.part_image].push(v.image); // the actual image values you want to group
else groups[v.part_image] = [ v.image ];
});
// Now you can process each image and all its parts
You can iterate over all the keys in the object. Object.keys(groups)
for that.
来源:https://stackoverflow.com/questions/64715927/sort-array-and-group-it-with-specific-value