代码如下

function test() {
  let oldArr = [
    { id: "001", name: "赵大" },
    { id: "002", name: "钱二" },
    { id: "003", name: "孙三" },
    { id: "004", name: "李四" },
  ];
  let newArr = [
    { id: "002", name: "钱二" },
    { id: "003", name: "孙三" },
    { id: "005", name: "周五" },
    { id: "006", name: "吴六" },
  ];
  let deletedArr = [];
  let addedArr = [];
  oldArr.forEach((item) => {
    if (newArr.filter((v) => v.id == item.id).length == 0) {
      deletedArr.push(item);
    }
  });
  newArr.forEach((item) => {
    if (oldArr.filter((v) => v.id == item.id).length == 0) {
      addedArr.push(item);
    }
  });
  console.log("删除的内容", deletedArr);
  console.log("新增的内容", addedArr);
}

测试效果如下

在网上找了很多写法,但不知道为啥怎么写都不太对。所以自己弄了一个写法,可能写法有点笨,但好在我写的代码需求上数组不大,不会影响性能,如果有更好的写法,还望指教~


Jinyun
36 声望1 粉丝