首页 > 解决方案 > 在数组中分组相同的字符串并计算它们

问题描述

这是一个 Angular 项目,我有来自服务器的数据。我正在创建三个列表。我有三种情绪,每种情绪都有一个描述

for (const sentiment of this.dataSource.allFavourabilities) {
  if (sentiment.sentiment === 'Positive') {
    this.positiveList.push(sentiment);
  }

  if (sentiment.sentiment === 'Negative') {
    this.negativeList.push(sentiment);
  }

  if (sentiment.sentiment === 'Neutral') {
    this.neutralList.push(sentiment);
  }
}

这就是我 console.log 时的样子。

coverageId:137
description:"Positive"
id:119
sentiment:"Positive"

在 HTML 中,我将其列在三个 div 中,唯一不变的是显示为图标的情绪,描述可能不同。但是客户主要输入正面、负面或中性,所以我得到了一个包含相同数据的丑陋列表。我想过滤它,所以它是描述中的一个匹配字符串,并且我在描述中有 50 次是肯定的,在我的 HTML 中应该说

首选结果:

positive(50)
negative(2)
neutral

并不是

positive
positive
positive
positive etc.
negative
negative
neutral

这是我的 HTML:

<div class="form-item favourability-wrapper flex">
      <div class="column" *ngIf="positiveList">
        <div class="sentiment-label">Positive</div>
        <ng-container *ngFor="let a of positiveList">
          <div class="sentiment sentiment-positive ">
            <i class="fas fa-smile"></i>
            <div class="description">{{ a.description }}</div>
          </div>
        </ng-container>
      </div>
      <div class="column" *ngIf="negativeList">
        <div class="sentiment-label">Negative</div>
        <ng-container *ngFor="let b of negativeList">
          <div class="sentiment sentiment-neutral">
            <i class="fas fa-meh"></i>
            <div class="description">{{ b.description }}</div>
          </div>
        </ng-container>
      </div>
      <div class="column" *ngIf="neutralList">
        <div class="sentiment-label">Neutral</div>
        <ng-container *ngFor="let c of neutralList">
          <div class="sentiment sentiment-negative">
            <i class="fas fa-frown"></i>
            <div class="description">{{ c.description }}</div>
          </div>
        </ng-container>
      </div>
    </div>

标签: javascriptangulartypescript

解决方案


将其更改为显示长度的 html 元素

<ng-container *ngFor="let a of positiveList">
          <div class="sentiment sentiment-positive ">
            <i class="fas fa-smile"></i>
            <div class="description">{{ a.description }}</div>
          </div>
</ng-container>

<div *ngIf="positiveList">
    {{ '(' + (positiveList?.length || '0')+')' }}
</div>

推荐阅读