首页 > 解决方案 > 简化交集和析取的比较函数

问题描述

有没有一种简单的方法来实现这一点。

我有 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"}]
}

标签: javascript

解决方案


推荐阅读