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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With