排序数组并将其与特定值分组 [英] Sort array and group it with specific value

查看:69
本文介绍了排序数组并将其与特定值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含很多值的数组,如下所示:

I have an array with a lot of values looking like this :

我正在尝试通过对每个部分"进行分组来对数组进行排序.具有相同 part_image 值,然后呈现图像的图像,该值仅链接一次.

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.

我尝试使用groupBy函数,但没有成功,有人能解决这个问题吗?

I tried using the groupBy function but without success, does anyone have an approach for this ?

数组变量: 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>

推荐答案

请考虑以下代码段:

// 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

您可以遍历对象中的所有键. Object.keys(组).

You can iterate over all the keys in the object. Object.keys(groups) for that.

这篇关于排序数组并将其与特定值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆