javascript-比较数组对象并显示差异
作者:互联网
我有两个数组要比较,并检查其中一个数组中是否有已删除的项目.如果有区别,请告诉我(已删除的项目)
这是下面我想如何实现的代码:
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的过滤器?并且仅显示这些数组对象之间的区别.
所以基本上我希望看到的是这些数组之间的差异,因此在本例中记录id的差异:1,2,5,6,7,8
解决方法:
您可以选择Set
以获取差异.为了获得彼此的差异(对称差异),您需要同时获得两个差异.
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(' '));
标签:javascript,ecmascript-6,ecmascript-5 来源: https://codeday.me/bug/20191011/1894141.html