Find the variance between two arrays containing distinct elements

I have 2 arrays with a similar structure as shown below. My objective is to compare each field and store the items from the arrays that differ in a third array.

Arr1= [{ state:CA, id:1, name:aaa, product:car, color: white}, {...}] 

and so forth

Arr2= [{ id:1, name:bbb, product:car, color: white, mileage:30, type: sedan}, {...}] 

and so on

Arr3= [{ state: CA, id:1, name:aaa, product:car, color: white}], 

Error/result/difference = name (something along those lines)

The goal is to use the combination of id, make, product, and color as a key field for comparison with the second array. If there is a difference in any of these fields, then the entire object should be added to the third array.

Note: These two arrays have different sets of key-value pairs, with only a few common ones. The aim is to compare these common elements in each object in Arr1 with every object in Arr2, highlighting any differences.

Note#2: I am not interested in finding missing objects in either array; my focus is solely on identifying matching objects with perhaps one mismatched key value among the common keys.

The proposed solution does not align with my query. I hope I have clarified it adequately.

Answer №1

I found some parts of the question unclear, such as why type: sedan didn't end up in arr3. However, based on my understanding, this code should suit your requirements:

const arr1 = [
    { state: "CA", id: 1, name: "aaa", product: "car", color: "white" },
    { state: "NY", id: 2, name: "ccc", product: "bike", color: "red" },
  ];

  const arr2 = [
    { id: 1, name: "bbb", product: "car", color: "white", mileage: 30, type: "sedan" },
    { id: 2, name: "ddd", product: "bike", color: "blue", mileage: 15, type: "mountain" },
  ];

  const compare = (arr1, arr2) => {
    const result = [];

    arr1.forEach((item1, index1) => {
      const item2 = arr2.find((item2) => item1.id === item2.id);
      if (!item2) return;

      const keys1 = Object.keys(item1);
      const keys2 = Object.keys(item2);
      const commonKeys = keys1.filter(key => keys2.includes(key));

      let anyMismatch = false;

      commonKeys.forEach((key) => {
        if (item1[key] !== item2[key]) {
          anyMismatch = true;
        }
      });

      // If there is any mismatch in common keys, add the entire object from arr1 along with its index
      if (anyMismatch) {
        result.push({ ...item1, index: index1 });
      }
    });

    return result;
  };

  console.log(compare(arr1, arr2));

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

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

"Process the contents of a file by reading it line by line in a

Currently, I am reviewing the documentation for the nodejs readline module in order to tackle a task that involves reading a very large file line by line. The solution using readline seems promising, although I require it to read lines synchronously - mean ...

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...

Retrieve the initial span within a <div> by using the data-id

Looking to access the initial span element inside a div? To retrieve the DOM element of the div, use the following code snippet: helper: function(event,ui){ var dataId = $(this).data('id'); console.log($('[data-id=" ...

Transitioning from an asp.mvc application to a node.js application, with a strong emphasis on enhancing the design aspects

I am currently exploring different platforms to transition an existing application. The initial version was built using asp.mvc, but the majority of the code is in javascript with a simple asp mvc web service. As we plan to move forward, it seems logical t ...

Updating PHP query with JavaScript or jQuery: yea or nay?

I am currently working on a project where I need specific text fields to update periodically with information from a database. To achieve this, I am experimenting with using PHP within JavaScript (or JS in PHP?). My goal is to have these fields update with ...

An easy way to showcase Wikipedia's JSON data using JQuery

I would like to showcase the information found in the "extract" section of this JSON data retrieved from Wikipedia: { "query": { "normalized": [ { "from": "india", "to": "India" } ...

Implementing global event callback in JavaScript

Is there a way to globally add an `onerror` function for the `div.circle_thumb>img` event? Instead of adding an `onerror` event to each img tag individually, such as shown below. <div class="circle_thumb" ><img src="some/url" onerror="this.sr ...

What is the best way to access external value in an Angular directive?

check out this plunker link. HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> ...

Organizing checkboxes to store selected values in an array using Vue.js

I am looking to implement a feature where a user can select checkboxes from a grouped list populated by an API call. When a checkbox is selected, I want to add the corresponding object to an array linked to the v-model of the checkbox input. Below are the ...

Downloading a file through a JavaScript link in HTMLUnit: A step-by-step guide

Looking to download a file with HTMLUnit from a javascript link is proving to be quite challenging. The journey begins at this page. When clicking on the "Authenticate with Java Web Start (new method)" link, a .jnlp file is downloaded, initiating a Java pr ...

Generating interactive sound using Node.js

Issue My current application, a morse code translator, is experiencing difficulties in playing multiple sounds for user input. It seems that only a single sound is played even when the method is called multiple times. Additionally, the sound is being play ...

What is the established procedure for resetting all elements within an (X)HTML document?

Is there a way to reset elements without using a form like how it can be done with JavaScript? document.forms[0].reset(); I am utilizing AJAX, so do I need to loop through all the elements using JavaScript? ...

Guidelines on declining a pledge in NativeScript with Angular 2

I have encountered an issue with my code in Angular 2. It works fine in that framework, but when I tried using it in a Nativescript project, it failed to work properly. The problem arises when I attempt to reject a promise like this: login(credentials:Cr ...

Using ReactJS, the for loop can be utilized to dynamically create buttons and assign variables based on the integer being iter

I need some help with ReactJS. I'm trying to generate 10 buttons using a for loop and assign a variable with the iteration number, but when I use the function setMqty(i), it always returns 11 for all buttons. Can anyone help me figure out the correct ...

Adding custom properties to TreeNode in PrimeNg Tree Component [Angular5]

Is there a way to add a custom property to a TreeNode in PrimeNg Tree for Angular? For example, setting TreeNode.id = "DemoId" results in an error stating that "id" is an unknown property of TreeNode. I am seeking guidance on the correct method for adding ...

organizing components for identical items

I am dealing with a simplified array of objects containing various elements extracted from a database. My goal is to group classes together for each person in order to display them neatly in an HTML table as the final result. Currently, I am using the foll ...

Creating a notification for specific choices in a dropdown menu

I am working on a form that includes a select element with multiple options. Depending on the option selected, a different form will be displayed. My concern is if a user starts filling out one form and then decides to select another option, I want to add ...

Prevent multiple images from continuously changing their image sources

I have implemented the following script: $(function image_swap() { $('.mainthumb').click(function () { $('.main').attr('src', this.src.replace('-thumb', '')) }); }); To allow my main image ...