最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript ES6 - count duplicates to an Array of objects - Stack Overflow

programmeradmin4浏览0评论

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:

ponent.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;
  }

ponent.html

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

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:

ponent.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;
  }

ponent.html

   <div *ngFor="let f of filteredArray">
      {{f}}
   </div>
Share Improve this question edited Apr 5, 2018 at 16:16 asked Apr 5, 2018 at 16:09 user7776077user7776077 1
  • I described this link above, it's not what i'm looking for – user7776077 Commented Apr 5, 2018 at 16:15
Add a ment  | 

5 Answers 5

Reset to default 8

You can use reduce to summarize the array and map for form the desired output

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);

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

you can simply do it by using Lodash countBy function

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

You can simply do it by using array.reduce() method

const votes = ['Yes', 'Yes', 'Yes', 'No', 'No', 'Absent'];

const result = votes.reduce((prevValue, vote) => {
    if (prevValue[vote]) {
        prevValue[vote]++;
    } else {
        prevValue[vote] = 1;
    }
    return prevValue;
}, {});

console.log(result);

Output : { Yes: 3, No: 2, Absent: 1 }

let obj = ['a', 'a', 'ab', 'b', 'b', 'c'];
let result = obj.reduce((acc, val) => { 
acc[val] = acc[val] ? ++acc[val] : 1; 
return acc; 
}, {})  
console.log(result);

发布评论

评论列表(0)

  1. 暂无评论