Subtract array of objects from array of objects

Viewed 113

I know similar questions have been posted but they never seems to target the same problem.

I want to remove Objects contained in the second array (itemsToRemove) from the first array (allItems).

allItems = [{x:1, y:2}, {x:1, y:1}, {x:4, y:1}]

itemsToRemove = [{x:1, y:2}]

result = [{x:1, y:1}, {x:4, y:1}]

I've tried many ways, but it somehow fails at the find() condition

      const result = allItems.filter((itemFromAllItems ) => {
                return !itemsToRemove.find( itemToRemove => {
                    return itemFromAllItems.x === itemToRemove.x && itemFromAllItems.y === itemToRemove.y
                })
            })
3 Answers

Assuming that your objects only have x and y values, This will work.

var allItems = [{x:1, y:2}, {x:1, y:1}, {x:4, y:1}]

var itemsToRemove = [{x:1, y:2}]

var result = allItems.filter(e => !itemsToRemove.some(s => s.x === e.x && s.y === e.y));

console.log(result);

Hope this helps

If you simply want to filter you can use filter and some to get the data you want however if you want to literally remove the object from the array you can use this instead

allItems = [{x:1, y:2}, {x:1, y:1}, {x:4, y:1},{x:4, y:1},{x:4, y:1}]
itemsToRemove = [{x:1, y:2},{x:4, y:1}]
 for(let i=0;i<allItems.length;i++){
   o=allItems[i]
  itemsToRemove.some(v=>{if(o.x==v.x &&o.y==v.y) allItems.splice(i,1),i--})
 }
console.log(allItems)

This takes the 2 arrays, compares the values, and makes a new one with only the results that don't match.

<script>
allItems = [{x:1, y:2}, {x:1, y:1}, {x:4, y:1}];
itemsToRemove = [{x:1, y:2}]
result = [];
for(var i = 0; i < allItems.length; i++){
  for(var j = 0; j < itemsToRemove.length; j++){ 
    if(JSON.stringify(allItems[i]) !== JSON.stringify(itemsToRemove[j])){
      result.push(allItems[i]);
    }
  }
} 
console.log(result);
</script>
Related