JS求两个对象数组的差集

let arr1 = [ 
    {fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36"}
];
let arr2 = [ 
    {fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34"},
    {fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33"}
];



JS求两个对象数组的差集

[
        {fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35"},
        {fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36"}
]
阅读 2.5k
评论 更新于 2019-04-28
    5 个回答
    言月
    • 1.5k

    这样试试。。。

    clipboard.png

    let arr1 = [
      { fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34" },
      { fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33" },
      { fpcid: "2da37fdfe66140089dc3367b21cc6196", fpcNameCode: "35" },
      { fpcid: "2da37fdfe66140089dc3367b21cc6197", fpcNameCode: "36" }
    ];
    let arr2 = [
      { fpcid: "2da37fdfe66140089dc3367b21cc6194", fpcNameCode: "34" },
      { fpcid: "2da37fdfe66140089dc3367b21cc6195", fpcNameCode: "33" }
    ];
    
    function diffset(arr1, arr2) {
      var l, shortArr, longArr;
      if (arr1.length > arr2.length) {
        shortArr = arr2;
        longArr = JSON.parse(JSON.stringify(arr1));
      } else {
        shortArr = arr1;
        longArr = JSON.parse(JSON.stringify(arr2));
      }
      l = shortArr.length;
      for (var i = l - 1; i >= 0; i--) {
        let { fpcid, fpcNameCode } = shortArr[i]
        let t = longArr.findIndex(item => item.fpcid === fpcid && item.fpcNameCode === fpcNameCode)
        if (t < 0) {
          longArr.push(arr2[i])
        } else {
          longArr.splice(t, 1)
        }
      }
      return longArr;
    }
    console.table(diffset(arr1, arr2))
    评论 赞赏 2019-04-29