简体   繁体   中英

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. Is there an easy way to do this besides looping through all properties and comparing them to find the elements in the first array that 100% match the elements in the second array and then deleting from the first array?

I'm basically doing a jQuery.grep() on an array of objects and the resulting array from this grep I want to delete from the array I passed into it.

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) {
  return condition(val);
});

Change it to

array = $.map( array, function(val) {
  if(condition(val))
    return null;
  return val;
});

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.

function deleteMatchingValues( 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM