Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select distinct property values of a list of object in Angular [duplicate]

I have the below list of object:

var data = [
    {
        "AcctId": 100,
        "Value": true
    },
    {
        "AcctId": 200,
        "Value": false
    }
]

I want to select distinct AcctId like this:

Output: [100, 200]

I've tried to use the angular filter method:

var newData = data.filter(r => r.AcctId);

But, it's returning the same list as input. can anyone please guide me on what I'm doing wrong?

like image 354
SUBHAJIT GANGULI Avatar asked Nov 25 '25 02:11

SUBHAJIT GANGULI


1 Answers

Try like this:

Working Demo

this.result = Array.from(new Set(this.data.map(x => x.acctId)));

or,

 constructor() {
    this.result = this.GetDistinctValues(this.data, "acctId").map(x => x.acctId);
  }

  GetDistinctValues(Source: Array<any>, FilterKey: string = null): Array<any> {
    let DistinctArray = [];
    try {
      Source.forEach(e => {
        if (FilterKey !== null && FilterKey !== undefined && FilterKey !== "") {
          if (
            DistinctArray.filter(DE => DE[FilterKey] === e[FilterKey]).length <=
            0
          )
            DistinctArray.push(e);
        } else {
          if (DistinctArray.indexOf(e) === -1) DistinctArray.push(e);
        }
      });
    } catch (error) {
      DistinctArray = [];
    }
    return DistinctArray;
  }

Demo 2

like image 160
Adrita Sharma Avatar answered Nov 27 '25 16:11

Adrita Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!