JavaScript ES6-将重复项计数到对象数组 [英] JavaScript ES6 - count duplicates to an Array of objects
问题描述
我正在为我的产品列表创建一个过滤器,以计算所有生产者并按以下方式显示:
I'm creating for my list of products a filter to count all producers and display like this:
苹果(3)
我从数组中删除了重复项:["Apple","Apple","Apple"]我使用了此链接:
I eliminated the duplicates from array: ["Apple","Apple","Apple"] I used this link:
但是我的问题是我想从数组中计数这些元素并在对象数组中显示它们,因为我需要稍后对其进行迭代.
But my problem is that I want to count these elements from array and display them in an Array of Objects cause i need to iterate it later.
从上述一系列苹果中,我需要结果:[{"Apple":3},{...},{...}]
From this Array of Apples above i need result: [{"Apple": 3},{...},{...}]
我正在尝试执行此操作,但是它返回了我对象,并且在此之后我无法进行迭代:如何计算JavaScript数组中的重复值
I was trying to do this but it returns me object and I can't iterate after it: How to count duplicate value in an array in javascript
我需要一个对象数组,该数组不可重复
我正在使用Angular 4.
I'm using 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>
推荐答案
此处:
const array = ["a", "a", "b"]
const result = { }
for (let i = 0; i < array.length; i++) {
result[array[i]] = (result[array[i]] || 0) + 1
}
Object.keys(result).map(key => ({ [key]: result[key] }))
最后一行是
我试图这样做,但是它返回了我对象
I was trying to do this but it returns me object
这篇关于JavaScript ES6-将重复项计数到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!