javascript - 在数组中分组相同的字符串并计算它们
问题描述
这是一个 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>
解决方案
将其更改为显示长度的 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>
推荐阅读
- python - 从网站上抓取文本值但得到 AttributeError
- docker - How do I make Synology Diskstation port visible to computer for Docker app
- c - C:在cygwin上使用Openssl时声明冲突
- python - 打印错误的python
- python - 如何使用 BeautifulSoup 抓取网站
- sorting - Clojure 重排序函数
- windows - 阻止用户意外执行 .bat 文件
- angular - 如何针对 localhost API(Dev App)运行 Ionic App
- r - 存储循环中的值
- php - 如何在 laravel 中与数据中心 ID 同步