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'}];
dheena
  • 85
  • 3
  • 6
  • 15

1 Answers1

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)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73