Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript filter array of objects by an array

Tags:

javascript

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

like image 847
anand Avatar asked Jan 23 '18 12:01

anand


4 Answers

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)));
like image 138
Aravind Avatar answered Oct 17 '22 22:10

Aravind


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);
like image 33
pwolaq Avatar answered Oct 17 '22 20:10

pwolaq


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/

like image 26
Wyns Avatar answered Oct 17 '22 20:10

Wyns


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; }
like image 2
Nina Scholz Avatar answered Oct 17 '22 21:10

Nina Scholz