JavaScript ES6 - 计算对象数组的重复项

1 html javascript arrays typescript angular

我正在为我的产品列表创建一个过滤器来计算所有生产者并显示如下:

苹果 (3)

我从数组中消除了重复项:["Apple","Apple","Apple"] 我使用了这个链接:

获取数组中的所有非唯一值(即:重复/多次出现)

但我的问题是我想从数组中计算这些元素并将它们显示在一个对象数组中,因为我需要稍后对其进行迭代。

从上面的这个苹果数组中,我需要结果:[{"Apple": 3},{...},{...}]

我试图这样做,但它返回了我的对象,我无法在它之后迭代: 如何在 javascript 中计算数组中的重复值

我需要一个不重复的对象数组

我正在使用 Angular 4。

我的代码:

组件.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;
  }
Run Code Online (Sandbox Code Playgroud)

组件.html

   <div *ngFor="let f of filteredArray">
      {{f}}
   </div>
Run Code Online (Sandbox Code Playgroud)

Edd*_*die 6

您可以使用reduce汇总数组并map形成所需的输出

let obj = ["Apple", "Apple", "Apple", "Orange"];

let result = Object.values(obj.reduce((c, v) => {
  c[v] = c[v] || [v, 0];
  c[v][1]++;
  return c;
},{})).map(o=>({[o[0]] : o[1]}));

console.log(result);
Run Code Online (Sandbox Code Playgroud)