简体   繁体   English

从对象数组中减去对象数组

[英]Subtract array of objects from array of objects

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 )中删除第二个数组( itemsToRemove )中包含的对象。

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我尝试了很多方法,但它在find()条件下以某种方式失败

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

Assuming that your objects only have x and y values, This will work.假设您的对象只有 x 和 y 值,这将起作用。

 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 => sx === ex && sy === 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如果你只是想过滤,你可以使用filtersome来获取你想要的数据,但是如果你想从数组中删除 object 你可以使用它来代替

 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(ox==vx &&o.y==vy) 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.这需要 2 个 arrays,比较值,然后创建一个只有不匹配结果的新值。

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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