-2

I have the following two arrays:

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

I want to remove objects present in ObjectArray that have id's equal to the values present in SimpleArray.

Phiter
  • 14,570
  • 14
  • 50
  • 84
Taahaa
  • 13
  • 3
  • Loop through `ObjectArray` and remove items where the `id` is in `SimpleArray` – Rory McCrossan Jun 08 '16 at 16:40
  • Possible duplicate of [removes elements from array javascript (contrary intersection)](http://stackoverflow.com/questions/29715271/removes-elements-from-array-javascript-contrary-intersection) – 1983 Jun 11 '16 at 11:38

1 Answers1

0

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188