Taahaa Taahaa - 5 months ago 8
jQuery Question

How to remove objects from an array having values that are present in an other simple array (jquery)

I have the following two arrays:

SimpleArray = [2,3];
ObjectArray = [{
id: 1,
name: charles
},{
id: 2,
name: john
},{
id: 3,
name: alen
},{
id: 4,
name: jack
}];


I want to remove objects present in
ObjectArray
that have id's equal to the values present in
SimpleArray
. Any help will be appreciated.

Answer

If you want to delete data from original array then use Array#splice() method

SimpleArray = [2, 3];
ObjectArray = [{
  id: 1,
  name: 'charles'
}, {
  id: 2,
  name: 'john'
}, {
  id: 3,
  name: 'alen'
}, {
  id: 4,
  name: 'jack'
}];

for (var i = 0; i < ObjectArray.length; i++) {
  if (SimpleArray.indexOf(ObjectArray[i].id) > -1) {
    ObjectArray.splice(i, 1);
    i--;
  }
}

console.log(ObjectArray);


In case you need to generate new filtered array then use Array#filter() method

SimpleArray = [2, 3];
ObjectArray = [{
  id: 1,
  name: 'charles'
}, {
  id: 2,
  name: 'john'
}, {
  id: 3,
  name: 'alen'
}, {
  id: 4,
  name: 'jack'
}];

var res = ObjectArray.filter(function(v) {
  return SimpleArray.indexOf(v.id) > -1
})

console.log(res);