Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of objects by array of ids

Tags:

I have an array activeIds of ids of services and there is another array servicesList which contains objects of services.

Example: -

activeIds = [202, 204] serviceList = [{                   "id":201,                 "title":"a"                },                {                   "id":202,                 "title":"a"                },                {                   "id":203,                 "title":"c"                },                {                   "id":204,                 "title":"d"                },                {                   "id":205,                 "title":"e"                }]; 

I want all the services(obj) whose ids are not a part of the first array i.e., activeIds. From the above example code I want service obj of ids 201,203,205

Final output -

expectedArray = [{                   "id":201,                 "title":"a"                },                {                   "id":203,                 "title":"c"                },                {                   "id":205,                 "title":"e"                }]; 

Here is my attempt to code. But it is not correct at all. Please help-

    const activeIds = e; // [202, 204]     const obj = [];     this.serviceList.map((s: IService) => {         activeIds.map((id: number) => {             if (id !== s.id) {                 obj.push(s);             }         });     }); 
like image 839
Yashwardhan Pauranik Avatar asked Feb 17 '18 18:02

Yashwardhan Pauranik


People also ask

How do you filter an array of objects with another array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.


1 Answers

You can simply use array.filter with indexOf to check the matching element in the next array.

var arr = serviceList.filter(item => activeIds.indexOf(item.id) === -1); 

DEMO

let activeIds = [202, 204] let serviceList = [{                   "id":201,                 "title":"a"                },                {                   "id":202,                 "title":"a"                },                {                   "id":203,                 "title":"c"                },                {                   "id":204,                 "title":"d"                },                {                   "id":205,                 "title":"e"                }];   let  arr = serviceList.filter(function(item){       return activeIds.indexOf(item.id) === -1;     });      console.log(arr);
like image 92
Sajeetharan Avatar answered Oct 12 '22 15:10

Sajeetharan