问题描述
我有两个要比较的数组,并检查其中一个数组中是否有删除的项目。如果有显示差异(已删除项目)
I have two arrays which I want to compare and check if there is an deleted item in one of these arrays. If there is show me the difference (deleted item)
以下是我想要实现此目标的代码:
Here is the code below how I would like to achieve this:
var completedList = [{id:1},{id:2},{id:3},{id:4},{id:7},{id:8}];
var invalidList = [{id:3},{id:4},{id:5},{id:6}];
// filter the items from the invalid list, out of the complete list
var validList = completedList.map((item) => {
console.log(item.id)
return item.id;
//console.log(invalidList.id);
}).filter(item => {
Object.keys(invalidList).map(key => {
console.log(invalidList[key].id)
//return !invalidList[key].id.includes(item.id);
});
})
console.log(validList); // Print [1,2,7,8]
// get a Set of the distinct, valid items
var validItems = new Set(validList);
但这会给我带来很多 id的
我如何映射数组和过滤器对象属性id?并且只显示这些数组对象之间的区别。
But this returns me a lot of id's
how can I map through both array's and filter on object property id? And only show the difference between these array objects.
所以基本上我期望看到这些数组之间的差异所以记录id的差异所以在这个例子中: code> 1,2,5,6,7,8
So basically what I expect is to see the difference between those arrays so log the differences in id's so in this example: 1,2,5,6,7,8
推荐答案
你可以参加获得差异。为了获得彼此之间的差异(对称差异),您需要获得两者之间的差异。
You could take a Set
for getting a difference. For getting the differences from each other (a symmetric difference), you need to get both differences.
const
difference = (a, b) => Array.from(b.reduce((s, v) => (s.delete(v), s), new Set(a))),
getId = ({ id }) => id;
var completedList = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 7 }, { id: 8 }],
invalidList = [{ id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }],
complete = completedList.map(getId),
invalid = invalidList.map(getId),
left = difference(complete, invalid),
right = difference(invalid, complete),
result = [...left, ...right]
console.log(result.join(' '));
console.log(left.join(' '));
console.log(right.join(' '));
这篇关于比较数组对象并显示差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!