Skip to content Skip to sidebar Skip to footer

Javascript Delete From Array Based On Another Array With Same Object And Values

I have an array of objects (all the same object type). I have another array of the same object type in which I want to use to tell me which objects to delete from the first array.

Solution 1:

Instead of using jQuery.grep(), to obtain a new array, replace it with jQuery.map(), returning the same object if it must be kept, or null if you want to remove it.

If for instance your code is

var toBeDeleted = $.grep(array, function(val) {
  returncondition(val);
});

Change it to

array = $.map( array, function(val) {
  if(condition(val))
    returnnull;
  returnval;
});

Solution 2:

If all it is is an array of values that need to be deleted from another array then looping through the arrays is really quite easy.

functiondeleteMatchingValues( target, toBeDeleted, oneMatch ) {
    var i = target.length, j = toBeDeleted.length;

    while( i-- ) {while( j--) {if( target[i] === toBeDeleted[j] ) {
                target.splice(i,1);
                if( oneMatch ) { break; }
            }
        }
        j = toBeDeleted.length;
    }
}

The above function includes a parameter for when you know there is only single instances of the value in the array.

Post a Comment for "Javascript Delete From Array Based On Another Array With Same Object And Values"