Rhea
Rhea

Reputation: 401

how to find mismatch elements between two nested array in react

I have two arrays below. array 1:

{
  "0":{
  "countries":{
     "BDI":{
        "count":1
     },
     "IRN":{
        "count":1
     }
  },
  "checkId":"16835659691517226105"
},
 "1":{
  "countries":{
     "ZAF":{
        "count":2
     }
  },
  "checkId":"144165083478491226"
 }
}

array2:

{
 "0":{
  "countries":{
     "AIA":{
        "count":2
     }
  },
  "checkId":"144165083478491106"
 },
  "1":{
  "countries":{
     "BDI":{
        "count":1
     },
     "IRN":{
        "count":1
     },
     "ATA":{
        "count":5
     }
  },
  "checkId":"16835659691517226105"
}
 
}

I want to find the mismatch and common element between the two arrays. currently, I am executing two for loops to find the matching element between two array-based on checkids but I am not able to find the non-common elements from these two. some code snippets

  array1.forEach(each => {
array2.forEach(compareTask => {
  var teastEach = Object.entries(compareTask.countries);
  if (each.checkId === compareTask.checkId) {
    firstCount = each.count
    secondCount = compareTask.count
    countDifference =  secondCount - firstCount

......

I am able to get the common checkids but not getting the non-common checkids. expected output:

    {
      "0":{
  "countries":{
     "ZAF":{
        "count":2
     }
  },
  "checkId":"144165083478491226"
  },
 "1":{
  "countries":{
     "AIA":{
        "count":2
     }
  },
  "checkId":"144165083478491106"
  }
  }

Upvotes: 2

Views: 448

Answers (1)

Sven.hig
Sven.hig

Reputation: 4519

From the comments it looks like you could use Map()

object1 = { "0": { countries: { BDI: { count: 1, }, IRN: { count: 1, }, }, checkId: "16835659691517226105", }, "1": { countries: { ZAF: { count: 2, }, }, checkId: "144165083478491226", }, };
object2 = { "0": { countries: { AIA: { count: 2, }, }, checkId: "144165083478491106", }, "1": { countries: { BDI: { count: 1, }, IRN: { count: 1, }, ATA: { count: 5, }, }, checkId: "16835659691517226105", }, };

map = new Map();
arr = [Object.values(object1), Object.values(object2)].flat();
result = [
  ...arr
    .reduce((r, o) => {
      const dupli = r.get(o.checkId);
      dupli ? r.delete(o.checkId) : r.set(o.checkId, o);
      return r;
    }, new Map())
    .values(),
];
console.log(result);

Upvotes: 2

Related Questions