Filter Array Of Objects By Array Of Ids
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 = [{
Solution 1:
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);
Solution 2:
You can do this with filter
and includes
methods.
const activeIds = [202, 204]
const serviceList = [{"id":201,"title":"a"},{"id":202,"title":"a"},{"id":203,"title":"c"},{"id":204,"title":"d"},{"id":205,"title":"e"}]
const result = serviceList.filter(({id}) => !activeIds.includes(id));
console.log(result)
Solution 3:
Use filter
& indexOf
method.indexOf
will check if the current id is present in activeIds
array
var activeIds = [202, 204]
var serviceList = [{
"id": 201,
"title": "a"
},
{
"id": 202,
"title": "a"
},
{
"id": 203,
"title": "c"
},
{
"id": 204,
"title": "d"
},
{
"id": 205,
"title": "e"
}
];
var filteredArray = serviceList.filter(function(item) {
return activeIds.indexOf(item.id) === -1
});
console.log(filteredArray)
Solution 4:
you can combine indexOf
to check if the current id is on the active array and filter the array.
Post a Comment for "Filter Array Of Objects By Array Of Ids"