What is the best way to identify and retrieve the objects that do not match when comparing two arrays of objects

obj1 represents the original object while obj2 symbolizes the modified object. The goal is to extract the key-value pairs and types for all changed objects within the obje2 array of objects.

Therefore, I am looking for a solution where if the values for "name" or "id" are different in obj2, then return the object along with its 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 can one accomplish such a task?

Answer №1

To identify the variance, follow these steps:

  1. Map out all the updated platforms (including type and games)
  2. Filter the updated games and pinpoint the original game by ID
  3. Arrange the games within each platform and specify the type for comparison

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

const findDifference = (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; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with OpenCL: Values in array getting replaced

I've run into an issue where my existing array elements are being replaced by new values. Purpose of the Code Originally, I had an array with 100 elements, all generated from a sine function. The goal was to use this array as a FIFO buffer to comput ...

What is the process for exporting all sub-module types into a custom namespace?

When we import all types from a module using a custom-namespace, it appears to work smoothly, for example: import * as MyCustomNamespace from './my-sub-module' We are also able to export all types from a module without creating a new namespace, ...

Synchronous CORS XHR encounters issues with 302 redirect, while asynchronous function successfully redirects

Why does Firefox seem to be the only browser that doesn't throw an error when performing a synchronous request? Any insights on this peculiar behavior? // Ensure your JS console is open when running this script var url = '//api.soundcloud.com/ ...

Is there a way to ensure that the function within the 'for loop' is executed prior to sending the response in NodeJS?

Utilizing bluebird for this task, my main goal is to ensure that the function `get_like_status(email, results[i].id)` located at the end of the for loop runs before sending out the headers. Currently, I am encountering an issue where the array list retur ...

In the world of node.js, functions almost always have a tendency to

As a beginner in the world of nodejs, I am diving into various guides and screencasts to grasp the basics. One aspect that has caught my attention is the handling of async/sync operations, reading files, and understanding how nodejs deals with callbacks/re ...

Creating an Array Using Temporary Arrays

I have a file containing rows of random integers separated by "::". For example: "1 2 3::4 5:: 6 7 8 9::10 11 12::13" My goal is to create an array where each row is combined in a specific order: taking the second row and placing it at the end of the fir ...

I can't quite understand the reasoning behind why this specific function is designed to output

I've been working on a JavaScript exercise and struggling to understand the logic behind it. The exercise involves a function named "mystery" that utilizes several basic functions to return an array in reversed order. Despite spending hours trying to ...

An error occurred due to a state update being attempted on an unmounted component. The solution is to properly cancel all subscriptions and asynchronous tasks in a

Currently, I am attempting to utilize ListEmptyComponent within a FlatList. If there is no data present, I intend to display ListEmptyComponent={} However, in the Loadingsecond component, I am using useEffect to render when loading is true; if there is s ...

The changes made to $scope in AngularJS are not being displayed in the view

The View Section <div class="col-sm-8" data-ng-init="init_enable_disable()"> <select class="form-control" style="margin-top: 5px;" data-ng-model="schedule.scheduleType" data-ng-change="enable_disableDiv(schedule.scheduleType);"> ...

What is the process for removing a record with identical IDs from two collections in a MongoDB database?

I am facing an issue with deleting a record from two different collections in MongoDB. The problem occurs when trying to remove a record with the same ID from both collections simultaneously. userRouter.post('/deleteProject', function (req, res) ...

When you assign the page results from the scrape-it npm to a variable, it will return a Promise with the status of "pending."

I recently downloaded scrape-it from NPM as a dependency and I'm trying to store the results in a variable instead of using a callback function. When I run the code snippet provided in the scrape-it documentation: var myVar = scrapeIt("http://ionicab ...

In ReactJS, the import module.fucntion is functioning properly, however, when attempting to import { function } from '../../module', it is not working as

Encountering import issues, specifically when using the following code: import module from '../../module' console.log(module.func) The function is printed as expected. However, when trying this approach: import { func } from '../../module&a ...

Having trouble with fetching data in React from a URL?

When attempting to send a post request to a specific URL without proxy settings, I encountered a CORS error. After setting up a proxy, the URL was still pointing to localhost. The error persists even after attaching my proxyfile.js and including the code s ...

Having trouble with implementing the .addclass function in a dice roller project

I'm looking to have the element with id=die load initially, and then on a button click event labeled "click me," apply the corresponding CSS class such as 'die1,' 'die2,' and so forth. function roll() { var die = Math.floor(Ma ...

Extract the response from codebird and store it in an array (or access the JSON data from the codebird's reply)

I am currently working on retrieving data from Twitter using codebird in my JavaScript script. The issue I am facing is that codebird's response is in the form of an object rather than JSON. As a result, I am unable to use eval() to convert the JSON t ...

Showing a notification that is persistent and not dismissible

Hello everyone! I've been struggling with a problem on the RPS project for quite some time now. The issue arises when I try to display a message for a tie in the game, but I can't seem to find a solution to make it disappear when the round is not ...

Add to the current values of the REACT Form template property

I am new to working with REACT and I have been exploring whether it is possible to append a REACT Form control property value in order to enhance its functionality. To streamline the validation process, I have created a validation template that leverages ...

A new Vue component is regenerated after the creation method is called

I am facing an issue with setting the margin of an image to display it in the center of the page when the image dialog is created. I have calculated the margin in the component's created method and everything seems fine during debugging as the image i ...

Adding setTimeout within the Axios Scope can enhance the functionality and performance of your

Show an alert in the catch block of Axios. The issue at hand: Error message does not disappear after the specified time when using setTimeout. ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...