I am trying to remove objects from array based on value which is not matching.
This is my items array:
var items = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
var arr=["88","108"];
Here I am able to removing objects from array based on matching values..But I want to keep matching value objects and need to remove unmatched objects.
This is how I'm removing matching objects from array.
for(let i in arr) {
items = items.filter(function(item) {
return item.id !== arr[i];
});
}
5 Answers 5
You may use Array.filter along with Array.includes:
var items = [{"id":"88","name":"Lets go testing"},{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}];
var arr = ["88", "108"];
const result = items.filter(item => arr.includes(item.id));
console.log(result);
Comments
Use indexOf to determine the occurrence.
var items = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
var arr=["88","108"];
const filteredItems = items.filter(item => {
if (arr.indexOf(item.id)>-1) {
return item
}
})
console.log(filteredItems)
Comments
items = items.filter(function(item) {
return arr.indexOf(item._id)!=-1
});
Comments
You can convert your items array into a look-up table (a Map of ids which point to your actual object), and then .map() each on your arr. This approach is particularly useful if you have lots of data in items or arr as it is efficient:
const items = [{"id":"88","name":"Lets go testing"},{"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}];
const lut = new Map(items.map(({id, ...r}) => [id, {id, ...r}]));
const arr = ["88", "108"];
const result = arr.map(id => lut.get(id));
console.log(result);
If you can have multiple items which have the same id, then you can use .reduce() with .flatMap():
const items = [{"id":"88","name":"Lets go testing"}, {"id":"99","name":"Have fun boys and girls"},{"id":"108","name":"You are awesome!"}];
const lut = items.reduce((acc, obj) => {
acc[obj.id] = acc[obj.id] || [];
acc[obj.id].push(obj);
return acc;
}, {});
const arr = ["88", "108"];
const result = arr.flatMap(id => lut[id]);
console.log(result);
Comments
Solution -
var items = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
];
var arr = ["88","108"];
items = items.filter( (item) => arr.includes(item.id) );
items.filter( item => arr.includes( item.id ) )