[Fixed] JavaScript ES6 – count duplicates to an Array of objects

Issue

I’m creating for my list of products a filter to count all producers and display like this:

Apple (3)

I eliminated the duplicates from array: [“Apple”,”Apple”,”Apple”] I used this link:

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

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.

From this Array of Apples above i need result: [{“Apple”: 3},{…},{…}]

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

I need an Array of Objects it’s not duplicated

I’m using Angular 4.

My code:

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>

Solution

Here:

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

That last line is the key for

I was trying to do this but it returns me object

Leave a Reply

(*) Required, Your email will not be published