0

I am trying to remove objects from an object array based on another int array using java script.

Int array contains ids from object array. I want to removes objects from object array which doesn't have id from Integer array.

Example:

var x =[{name : 'mark' , Id : '10' , color:'green'},
  {name : 'hen' , Id : '15' , color:'blue'} ,
  {name : 'joy' , Id : '30' , color:'yellow'},
  {name : 'mick' , Id : '15' , color:'red'},
  {name : 'nick' , Id : '40' , color:'black'}] ; 

var y =['40','15'];

From the above 2 arrays, I want to remove objects from x array whose id is not present in y array;

Result Should be :

x =[{name : 'hen' , Id : '15' , color:'blue'},
  {name : 'mick' , Id : '15' , color:'red'},
  {name : 'nick' , Id : '40' , color:'black'}];
0

1 Answer 1

6

You can use filter() and check if Id is in y array using includes()

var x = [{name : 'mark' , Id : '10' , color:'green'}, {name : 'hen' , Id : '15' , color:'blue'} , {name : 'joy' , Id : '30' , color:'yellow'}, {name : 'mick' , Id : '15' , color:'red'}, {name : 'nick' , Id : '40' , color:'black'}] ;
var y = ['40','15'];

const res = x.filter(a => y.includes(a.Id));
console.log(res)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.