簡體   English   中英

JavaScript ES6 - 計算對象數組的重復項

[英]JavaScript ES6 - count duplicates to an Array of objects

我正在為我的產品列表創建一個過濾器來計算所有生產者並顯示如下:

蘋果 (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;
  }

組件.html

   <div *ngFor="let f of filteredArray">
      {{f}}
   </div>

您可以使用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);

在這里:

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] }))

最后一行是關鍵

我試圖這樣做,但它返回了我的對象

你可以簡單地使用 Lodash countBy函數來完成

  filters() {
    this.category2 = this.category.map(value => value.producer);
    this.filteredArray = _.countBy(this.category2);
    console.log(this.filteredArray);
// Object {Apple: 3, Orange: 1}
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM