javascript - 简化交集和析取的比较函数
问题描述
有没有一种简单的方法来实现这一点。
我有 2 个对象数组(旧项目和新项目),我需要根据对象中的属性识别添加、删除和未更改的所有项目,并分别将对象推送到所需的概览变量对象数组中。
const compareGroups = (oldG, newG) => {
const overview = { added: [], removed: [], unchanged: [] };
const seen = [];
let newItem = null;
let found = false;
for (const i in newG) {
if (newG[i]) {
newItem = newG[i];
found = false;
for (const j in oldG) {
if (oldG[j]) {
if (oldG[j].email === newItem.email) {
overview.unchanged.push(newItem);
seen.push(newItem.email);
found = true;
break;
}
}
}
if (!found) {
seen.push(newItem.email);
overview.added.push(newItem);
}
}
}
for (const k in oldG) {
if (oldG[k]) {
if (!seen.includes(oldG[k].email)) {
overview.removed.push(oldG[k]);
}
}
}
return overview;
}
const oldG = [{email: 'a'}, {email:'b'}, {email:'c'}];
const newG = [{email: 'a'}, {email:'d'}, {email:'e'}];
console.log(compareGroups(oldG, newG));
预期输出:
{
"added": [{"email": "d"},{"email": "e"}],
"removed": [{"email": "b"},{"email": "c"}],
"unchanged": [{"email": "a"}]
}
解决方案
推荐阅读
- scala - 如何为每个测试场景加载配置?
- python - Python有效地从URL下载图像
- python - 在一台 PC 上但在另一台 PC 上找不到包中的子模块
- wso2 - 无法同步 WSO2 节点服务
- r - R 中是否有 randn('state',100) 的等效版本,就像在 MATLAB 上一样?我的输出变化太大,因为它在 R 上不存在
- mips - 有没有办法在 mips CPU 上加速 GraphicsMagick 的调整图像大小性能?
- json - 使用 thymeleaf 在浏览器中打印 Spring Boot JSON RESTful 响应
- networking - 如何通过网关通过内部网络在虚拟机上启用 Internet?
- php - PHP在没有API的情况下检查youtube频道是否存在
- node.js - 无法安装“@angular/cli”