Skip to content
Advertisement

Find and Remove Objects from Array with Identical Property

I have two arrays of objects, one with approx. 1800 items and the second with approx. 600 items. An example of the data in each array:

let exampleArray = [{ID:X2346,NAME:"someName"},{ID:X8847,NAME:"someName2"},...]

I need to compare the two arrays, and if the ‘ID’ value from an object in the large array is equal to the ID value from an object in the smaller array, remove the object entirely from the larger array, or leave the larger array with only objects that don’t exist in the smaller array based on property ‘ID’.

I have done this using two nested for loops, and it works, but I’m trying to improve the speed. I’ve read up on hash tables but I don’t think it can apply to this situation or I am not fully understanding how to use them. Is there a faster way to accomplish my goal?

for (let x=0;x<largeArray.length;x++){
  for (let y=0;y<smallerArray.length;y++){
    if(largeArray[x]['ID']===smallerArray[y]['ID']){
      largeArray.splice(x,1)
    }
  }
}

Advertisement

Answer

You can map all the IDs in the small array with Array.prototype.map():

const idsFilter = smallArray.map(item => item.ID);

then you can use it to filter out from the large array the items whose ID is included in idsFilter, using Array.prototype.filter():

const filteredLargeArray = largeArray.filter(item => !idsFilter.includes(item.ID));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement