Home > Enterprise >  How to compare two array of objects and return the not matching object?
How to compare two array of objects and return the not matching object?

Time:09-27

obj1 is the original object and obj2 is the changed object. I want to get the key , value pair and the type of all the changed object inside obje2 array of objects.

So, I need something like this where if "name" or "id" value is different in obj2 return the object along with the type.

changedObj = [
  {
    type:"mobile",
    name:"Temple Runs",
    id:2259
  },
  {
    type:"pc",
    name:"Pubgs",
    id:222
  }
]

obj1 = [
  {
    type: "mobile",
    games: [
      {
        name: "Temple Run",
        id: 2259,
      },
      {
        name: "Subway Surfer",
        id: 2271,
      },
      {
        name: "Pubg",
        id: 2272,
      },
    ],
  },
  {
    type: "pc",
    games: [
      {
        name: "Pubg",
        id: 222,
      },
      {
        name: "Fortnite",
        id: 2274,
      },
      {
        name: "Nfs",
        id: 2272,
      },
    ],
  },
];

obj2 = [
  {
    type: "mobile",
    games: [
      {
        name: "Temple Runs",
        id: 2259,
      },
      {
        name: "Subway Surfer",
        id: 2271,
      },
      {
        name: "Pubg",
        id: 2272,
      },
    ],
  },
  {
    type: "pc",
    games: [
      {
        name: "Pubgs",
        id: 222,
      },
      {
        name: "Fortnite",
        id: 2274,
      },
      {
        name: "Nfs",
        id: 2272,
      },
    ],
  },
];

How to achieve something like this ?

CodePudding user response:

In order to find the difference, you will need to:

  1. Map all of the updated platforms (type and games)
  2. Filter the updated games and locate the original game by ID
  3. Flat-map the games in each platform and include the type

const main = () => {
  const delta = diff(changed, data);
  console.log(delta);
};

const diff = (updated, original) =>
  updated
    .map(({ type, games }) => ({
      type,
      games: games
        .filter(({ name, id }) => original
          .find(platform => platform.type === type).games
          .find(game => game.id === id)?.name !== name)
      }))
    .flatMap(({ type, games }) =>
      games.map(({ name, id }) =>
        ({ name, id, type })));

const data = [{
  type: "mobile",
  games: [
    { name: "Temple Run", id: 2259 },
    { name: "Subway Surfer", id: 2271 },
    { name: "Pubg", id: 2272 }
  ],
}, {
  type: "pc",
  games: [
    { name: "Pubg", id: 222 },
    { name: "Fortnite", id: 2274 },
    { name: "Nfs", id: 2272 }
  ]
}];

const changed = [{
  type: "mobile",
  games: [
    { name: "Temple Runs", id: 2259 },
    { name: "Subway Surfer", id: 2271 },
    { name: "Pubg", id: 2272 }
  ],
}, {
  type: "pc",
  games: [
    { name: "Pubgs", id: 222 },
    { name: "Fortnite", id: 2274 },
    { name: "Nfs", id: 2272 }
  ]
}];

main();
.as-console-wrapper { top: 0; max-height: 100% !important; }

  • Related