0

I have a JavaScript array with objects and an array having some Ids. What I want is to compare the objects in the array with the array of ids and if any id is found in an object, I want to remove that element from the array. Doing this the result shows undefined in place of deleted element.

var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}]
var arr = ["2","5"];
for (var i = 0; i < data.length; i++) {
    for(var j=0;j<arr.length;j++){
        if (arr[j]==data[i].id ) {
            delete data[i];
        }
    }
}

The result shows [undefined,object object,object object,undefined]. Is there any way to get only [object object,object object]?

Abhinav Parashar
  • 619
  • 4
  • 11
  • 27
  • You removed the object. However, you haven't removed an item from the array. You need to remove it just like you remove items from an array according to the article provided by @JeffMercado. – Yeldar Kurmangaliyev Sep 30 '15 at 05:42
  • Try `data = data.filter(Boolean);` after deleting the items. –  Sep 30 '15 at 05:54

1 Answers1

0
  1. use splice instead of delete
  2. loop array from length-1 to 0, otherwise you'll miss deal with some data.
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}];
var arr = ["2","5"];
for (var i = data.length-1; i >= 0; i--) {  
    for(var j = 0;j < arr.length;j++){  
        if (arr[j]==data[i].id ) {  
            data.splice(i,1);
        }
    }
}
console.log(data);
Fancyoung
  • 2,313
  • 26
  • 32
  • This is not going to work, because `splice` changes the shape of the array. To test this, try a test case where there are two deletable entries immediately next to each other. The second deletable entry will be skipped and not deleted. –  Sep 30 '15 at 06:02
  • this procedure will cause problem .. like i=0 has id then it'll splice from it then previous 1 index's will come in the 0 th index – Anik Islam Abhi Sep 30 '15 at 06:02
  • if wanna splice with multiple indexes from an array you have to splice it from it's descending order like 5,4,3....1 – Anik Islam Abhi Sep 30 '15 at 06:03
  • I think that's what I do in step `2`. – Fancyoung Sep 30 '15 at 06:14