I have to filter an array of objects to get certain values based on an another array and distinct also
Data
var value:any[]
var inventory = [
{id: 1, quantity: 2, GroupId: 1},
{id: 2, quantity: 0, GroupId: 2},
{id: 1, quantity: 2, GroupId: 1}
];
//data from db
value = [1,2]
My code
var data = this.inventory .filter(x => x.GroupId == this.value );
Not able to get the filtered data, but returning empty array. Thanks in advance
You should be using includes
If you want to distinct by the id field here's a solution:
JSFiddle example: https://jsfiddle.net/7xnybhLv/1/
You could use the variable directly and use
Array#includes
.In your code you are comparing
GroupId
with an array. You should check if array containsGroupId
instead.Here is how to do it:
For better support you can replace Array.prototype.includes with Array.prototype.indexOf: