【发布时间】:2018-09-15 13:03:03
【问题描述】:
我正在为我的产品列表创建一个过滤器来统计所有生产者并显示如下:
苹果 (3)
我从数组中删除了重复项:["Apple","Apple","Apple"] 我使用了这个链接:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
但我的问题是我想从数组中计算这些元素并将它们显示在对象数组中,因为我需要稍后对其进行迭代。
从上面的这个苹果数组中我需要结果:[{"Apple": 3},{...},{...}]
我试图这样做,但它返回了我 object 并且我无法在它之后进行迭代: How to count duplicate value in an array in javascript
我需要一个对象数组它不是重复的
我正在使用 Angular 4。
我的代码:
component.ts
async ngOnInit() {
this.cart$ = await this.cartService.getCart();
this.subscription = this.productService.getAll().subscribe(products => {
this.category = products.filter(
products => products.category == this.name
);
this.filters();
});
}
filters() {
this.category2 = this.category.map(value => value.producer);
this.filteredArray = this.eliminateDuplicates(this.category2);
console.log(this.filteredArray);
}
eliminateDuplicates(arr) {
let i,
len = arr.length,
out = [],
obj = {};
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
}
component.html
<div *ngFor="let f of filteredArray">
{{f}}
</div>
【问题讨论】:
-
我在上面描述了这个链接,这不是我要找的
标签: javascript arrays html angular typescript