Jayden
Jayden

Reputation: 283

How to remove object from array except matching value?

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];
  });
}

Upvotes: 0

Views: 967

Answers (5)

Nick Parsons
Nick Parsons

Reputation: 50664

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);

Upvotes: 1

Varun
Varun

Reputation: 1

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) );

Upvotes: 0

Sagar Chaudhary
Sagar Chaudhary

Reputation: 1403

items = items.filter(function(item) {
    return arr.indexOf(item._id)!=-1
  });

Upvotes: 1

31piy
31piy

Reputation: 23859

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);

Upvotes: 2

thuva4
thuva4

Reputation: 1225

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)

Upvotes: 1

Related Questions