JavaScript - find matches and differences between two arrays based on keys, resulting in four arrays showing the matches and differences for each

Custom Interface -

interface Person {
    name: string;
    age: number;
    city: string;
    address?: string;
}

Data Arrays -

const people1: Person[] = [
  {
    name: "daniel",
    age: 21,
    city: 'NYC'
  },
  {
    name: "kosta",
    age: 28,
    city: "NYC"
  },
  {
    name: "yoav",
    age: 28,
    city: "NYC"
  }
];

const people2: Person[] = [{
    name: "daniel",
    age: 21,
    city: "NYC",
    address: 'E. 43'
  },
  {
    name: "simon",
    age: 24,
    city: "NYC",
    address: 'E. 43'
  },
  {
    name: "david",
    age: 22,
    city: "NYC",
    address: 'E. 43'
  },
  {
    name: "kosta",
    age: 28,
    city: "NYC",
    address: 'E. 43'
  }
];

Mapping keys for the data arrays -

const people1Map: ReadonlyMap<string, string | undefined> = new Map(
    people1.map(
        ({
            name, age, city, address
        }) => [
            `${name}|${age}|${city}`,
            address
        ]
    )
);

const people2Map: ReadonlyMap<string, string | undefined> = new Map(
    people2.map(
        ({
            name, age, city, address
        }) => [
            `${name}|${age}|${city}`,
            address
        ]
    )
);

Arrays for Matches and Unmatches -

let matchedPeople1: Person[] = []
let unmatchedPeople1: Person[] = []
let matchedPeople2: Person[] = []
let unmatchedPeople2: Person[] = []

Comparing data between arrays and storing matches or unmatches accordingly.

The desired output is as follows:

matchedPeople1:

[{ name: "daniel", age: 21, city: "NYC", address: 'E. 43' }, { name: "kosta", age: 28, city: "NYC", address: 'E. 43' } ]

matchedPeople2:

[{ name: "daniel", age: 21, city: "NYC", address: 'E. 43' }, { name: "kosta", age: 28, city: "NYC", address: 'E. 43' }]

unmatchedPeople1:

[{ name: "yoav", age: 28, city: "NYC" }]

unmatchedPeople2:

[{ name: "simon", age: 24, city: "NYC", address: 'E. 43' }, { name: "david", age: 22, city: "NYC", address: 'E. 43' }]

Answer №1

When determining a solution, it is essential to consider your specific requirements: What exactly defines a match? How should the match array be populated if there are discrepancies between the data sets? Should the arrays reference the original objects or duplicates of them?
Furthermore, it seems that arr1Match and arr2Match serve the same purpose and could be consolidated into one.

In any case, the suggested approach involves iterating through one array and checking for matches in the other array for each value. Any items that do not have a match will be placed in the unmatch arrays.

// Implement actual matching logic here
const isMatch = <T>(a: T, b: T) => Math.random() < 0.5;

const getMatches = <T>(arrOne: T[], arrTwo: T[]) => {
  const matches: T[] = [];
  const arrOneUnmatches: T[] = [];
  let arrTwoUnmatches: T[];

  // Creating a copy for ease of use
  const arrTwoCopy = [...arrTwo];

  arrOne.forEach(item => {
    // Searching for a match in array two
    const arrTwoMatchIndex = arrTwoCopy.findIndex(arrTwoItem => isMatch(item, arrTwoItem));
    if (arrTwoMatchIndex) {
      matches.push(item);

      // Removing the matched item from arrTwoCopy to track arrTwoUnmatches
      arrTwoCopy.splice(arrTwoMatchIndex, 1);
    } else {
      // No match found - add to arrOneUnmatches
      arrOneUnmatches.push(item);
    }
  })

  // Any remaining items in arrTwoCopy did not find a match in arrOne, so they have no match
  arrTwoUnmatches = arrTwoCopy;

  return { matches, arrOneUnmatches, arrTwoUnmatches }
}

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

What could be the reason for Spawn() not being invoked?

After working with node.js and express for some time, I have encountered a persistent bug in my code. In my service file, there is a resolved Promise where I call spawn(), but for some reason, the spawn code never gets executed (or if it does, ls.on(' ...

When attempting to select a HTML element within a <ng-template> tag using d3.select(), it will return null

I have a situation where I have an element < svg > inside an < ng-template > <div *ngIf="data == undefined; else elseBlock"> Sorry no data! </div> <ng-template #elseBlock> <svg id="areachart" width="100%" height="210 ...

Iterate through the JSON data values using a loop and showcase each one by presenting them in individual cards

I'm having trouble determining which type of loop to use in this situation because I am still learning jQuery and JS. On the result page, I have set up cards to separate each piece of data from the JSON file, but I am unsure how to actually display th ...

Spin a Material UI LinearProgress

I'm attempting to create a graph chart using Material UI with the LinearProgress component and adding some custom styling. My goal is to rotate it by 90deg. const BorderLinearProgressBottom = withStyles((theme) => ({ root: { height: 50, b ...

Sharing data between Jasmine JavaScript tests: a complete guide

Currently, I am conducting tests involving reading and writing data (to a server, to a mongo db). While I understand that I should be using mocks for this purpose, I have found a workaround to achieve my goal of writing a document, validating its accuracy ...

Key in the calculation on Keypup for multiple rows, one row at a time

I want to create a calculation function for a form with multiple rows. The goal is to determine the totals for each row by multiplying the cost and unit price, then inputting the result in the total field. Below is the script that I attempted: <scrip ...

Ways to verify if a JavaScript file has been successfully downloaded to the client's side

I encountered a strange issue with JavaScript recently. The webpage in question uses jQuery code for collecting data and performing input validation. If the validation passes, it then sends the data to the server. However, some users (around 10% or possib ...

You cannot add properties to an object within an async function

I am attempting to include a fileUrl property in the order object within an async function, but I am unable to make it work properly. My expectation is for the order object to contain a fileUrl property once added, but unfortunately, it does not seem to b ...

What is the mistake in my update function when working with nodejs and mongodb?

Greetings! I am a beginner in using nodejs and mongodb, and I am looking to create a function that updates the win, lose, and draw record in my userschema. Here is my Schema: UserSchema = new mongoose.Schema({ username:'string', passwor ...

Obtain an identifier to be used as dynamic data in an ajax request with jQuery

I am struggling to extract the id from links that trigger the same ajax function. I have over 30 links generated dynamically, as shown below: <a href="javascript:void(0)" id="105">Item 105</a> <a href="javascript:void(0)" id="379">Item 3 ...

Steer clear of mentioning unbound methods, as they can lead to accidental scoping errors with 'this' when invoking static methods

I've been working on a method map based on a query from the Stack Overflow post linked here to assist me in dynamically calling a static method. But, I keep encountering this error message: Avoid referencing unbound methods that could lead to uninte ...

Ways to incorporate a loading feature in javascript, jquery, and php as it runs?

I have created a form that, when clicked on, returns a value within the page. Below is my form. When the form is submitted, it takes some time to process. I would like to display a loading message while the code is being executed. Here is my form: <ht ...

I am looking to update the 'startbutton.href' value based on the dynamic change in 'img.src'. Unfortunately, the if-else statement has proven ineffective in achieving this

let index = 1; let images = [ './img/wok.jpg', './img/croissant.jpg', './img/salad.jpg' ]; let img = document.getElementById("section-1-img"); let startButton = document.getElementById('startButton& ...

What is the best way to link a file to index.html using feathers.js?

I am currently learning feathers and encountering a problem. I am attempting to include files similar to PHP's switch function. For instance: /src/middleware/index.js 'use strict'; const handler = require('feathers-errors/handler&ap ...

Insert this HTML table along with radio buttons into an Excel spreadsheet

My HTML table contains rows with a variety of content, including plain text characters and elements like radio buttons and lists. I want users to be able to copy-paste the table into MS Excel as plain text and have the radio button values replaced with "c ...

Decoding date formats using d3.js version 4

Currently diving into the world of coding with d3.js by working on my very first d3 mini project, following the Free Code Camp curriculum. The goal is to create a basic bar graph using this json file. However, I've hit a roadblock while trying to form ...

Updating reference value with a watcher using Vue 3 and the Composition API

I'm having trouble updating a ref within a watch function. My goal is to monitor changes in the length of an array, and if the new length is less than the old one, I want to update a specific ref called selectedTitle. setup() { const slots = useS ...

Adjust the CSS content using the data-content attribute to include line breaks

My current coding setup includes: <div id="mydiv" data-content="Loading..."></div> This is how I style it with CSS: #mydiv:after{ content: attr(data-content); height: 100%; opacity: 1; position: absolute; text-align: center; ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

Troubleshooting problem with tooltip display in d3 when using multiple data sources

I am currently working on a d3 chart that is generated from JSON data created with PHP. The process runs smoothly as the PHP accurately formats the JSON and the chart displays correctly. You can view the chart here. Additionally, I have provided the comple ...