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
console.log([
{id: 1, quantity: 2, GroupId: 1},
{id: 2, quantity: 0, GroupId: 2},
{id: 3, quantity: 2, GroupId: 1}
].filter(x => [1,2].includes(x.id)));
In your code you are comparing GroupId
with an array. You should check if array contains GroupId
instead.
Here is how to do it:
var data = this.inventory.filter(x => value.includes(x.GroupId));
For better support you can replace Array.prototype.includes with Array.prototype.indexOf:
var data = this.inventory.filter(x => value.indexOf(x.GroupId) !== -1);
If you want to distinct by the id field here's a solution:
var inventory = [
{id: 1, quantity: 2, GroupId: 1},
{id: 2, quantity: 0, GroupId: 2},
{id: 1, quantity: 2, GroupId: 1}
];
var value = [1,2]
var data = inventory.filter(x => value.indexOf(x.GroupId)>-1).filter((elem1, pos, arr) => arr.findIndex((elem2)=>elem2.id === elem1.id) === pos);
console.log(data);
JSFiddle example: https://jsfiddle.net/7xnybhLv/1/
You could use the variable directly and use Array#includes
.
var inventory = [{ id: 1, quantity: 2, GroupId: 1 }, { id: 2, quantity: 0, GroupId: 2 }, { id: 3, quantity: 2, GroupId: 1 }],
value = [1, 2],
data = inventory.filter(({ GroupId }) => value.includes(GroupId));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
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