Q:

Removing Multiple Objects from Javascript Array Breaks Half Way Through

I have an Array of a few hundred JSON Objects...
var self.collection = [Object, Object, Object, Object, Object, Object…]

Each one looks like this...
0: Object
   id: "25093712"
   name: "John Haberstich"

I'm iterating through the Array searching each Array.id to see if it matches any ids in a second Array...
   var fbContactIDs = ["1072980313", "2502342", "2509374", "2524864", "2531941"] 

   $.each(self.collection, function(index, k) {
        if (fbContactIDs.indexOf(k.id) > -1) {
            self.collection.splice(index, 1);
        };
    });

However this code only works to splice three of the Objects from the self.collection array and then it breaks and gives the following error:
Uncaught TypeError: Cannot read property 'id' of undefined 

The line that is causing the error is this one...
if (fbContactIDs.indexOf(k.id) > -1) {

Could anyone tell me what I'm dong wrong here?

A:

Because the length of collection will change, the trick is to loop from rear to front
for (var index = self.collection.length - 1; index >= 0; index--) {
    k = self.collection[index];
    if (fbContactIDs.indexOf(k.id) > -1) {
        self.collection.splice(index, 1);
    };
}

