What is the best approach to gather both the intersection and the complements of two arrays in a single operation?

Comparing Arrays -

const source = [1, 1, 1, 3, 4];
const target = [1, 2, 4, 5, 6];

Initializing Arrays -

const matches1 = [];
const matches2 = [];
const unmatches1 = [];

Array Matching Process -

for (const line of source) {
  const line2Match = target.find((line2) => {
    const isMatch = line === line2;
    return isMatch;
  });

  if (line2Match) {
    matches1.push(
      line
    );
    matches2.push(line2Match);
  } else {
    unmatches1.push(line);
  }
}

Current Output -

[ 1, 1, 1, 4 ] ​​​​​found in ​​​​​​​​matches1​​​

[ 3 ] ​​​​​added to ​​​​​​​​unmatches1​​​

[ 1, 1, 1, 4 ] ​​​​​at ​​​​​​​​matches2​​​

Desired Output -

[ 1, 4 ] ​​​​​should be in ​​​​​​​​matches1​​​

[ 1, 1, 3 ] ​​​​​should be in ​​​​​​​​unmatches1​​​

[ 1, 4 ] ​​​​​should be in ​​​​​​​​matches2​​​

Additional Functionality Request -

If a match occurs between source and target, the matched value should be removed from the target array. How can this be achieved?

Answer №1

The original poster raised a question about handling matching values between two arrays.

"What I would like to add is when source has a match with target, the value will be deleted from the target array, how can I achieve that?"

One approach is to manually remove the common item from the target array, essentially creating the relative complement of source in target, also known as the target difference.

Another method involves making a shallow copy of the target array and using it as an initial value for a reduce operation to avoid modifying the original target reference.

function collectIntersectionAndComplements(collector, sourceItem) {
  const { targetDiff } = collector;

  const targetIndex = targetDiff
    .findIndex(targetItem => targetItem === sourceItem);

  if (targetIndex === -1) {

    // collect the relative complement of target
    // in source ... vulgo ... the source difference.
    (collector.sourceDiff ??= [])
      .push(sourceItem)
  } else {

    // collect the intersection of both source and target ...
    (collector.intersection ??= [])
      .push(
        // ... by rejecting the common item from the original
        // target, thus actively mutating the latter, which leads
        // to ending up additionally with the relative complement
        // of source in target ... vulgo ... the target difference.
        targetDiff.splice(targetIndex, 1)[0]
      );
  }
  return collector;
}

const source = [1, 1, 1, 3, 4];
const target = [1, 2, 4, 5, 6];
const {

  intersection,
  sourceDiff,
  targetDiff,

} = source.reduce(collectIntersectionAndComplements, { targetDiff: [...target] });

console.log({ source, target, intersection, sourceDiff, targetDiff });
.as-console-wrapper { min-height: 100%!important; top: 0; }

@heyheyhey2 ... By the way, in the context of the Simple Theory of Sets, duplicate values are not permitted within arrays/lists/sets. Sets should only contain unique values.

Answer №2

Only considering matches for matches1: (similar process for matches2)

const source = [1, 1, 1, 3, 4];
const target = [1, 2, 4, 5, 6];

let matches1 = source.reduce((res, curr)  => {
    if (target.includes(curr) && !res.includes(curr)) {
        res.push(curr);
    }
    return res;
}, []
);

console.log(matches1)
//[1,4]

For unmatches1:

let unmatches1 = source.reduce((res, curr)  => {
    if ((target.includes(curr) && res[0].includes(curr)) || !target.includes(curr)) {    
        res[1].push(curr);
    }
    if (target.includes(curr)) {
        res[0].push(curr)
    }
    return res;
}, [[],[]]
)[1]

console.log(unmatches1)
//[1,1,3]

To get the unmatches2 result of [2,5,6] - simply switch out the source and target in the input or within the code, or enhance the code to produce both outputs simultaneously. It's straightforward.

Answer №3

It is important to note that in order for a single pass to occur, both arrays need to be sorted in ascending order.

function processArrays(){
    const arr1 = [0,1, 1, 1, 3, 4, 6,8,10];
    const arr2 = [-3,-4,1, 2, 4, 5, 6,25,26];

    let noMatchArray1=[];
    let matchingElements=[];
    let noMatchArray2=[];
    let i=0,j=0;
    while(true){
        if(i>=arr1.length){
            for (;j<arr2.length;j++) noMatchArray2.push(arr2[j]);
            break;
        }
        else if (j>=arr2.length){
            for (;i<arr1.length;i++) noMatchArray1.push(arr1[j]);
            break;
        }
        else if(arr1[i]==arr2[j]){
            matchingElements.push(arr1[i++]);
            j++;
        }
        else if (arr1[i]<arr2[j]){
            let val=arr1[i++];
            if(noMatchArray1.length==0)noMatchArray1.push(val);
            else if(val != noMatchArray1[noMatchArray1.length-1])
                noMatchArray1.push(val);
        }
        else if (arr2[j]<arr1[i]){
            let val=arr2[j++];
            if(noMatchArray2.length==0)noMatchArray2.push(val);
            else if(val != noMatchArray2[noMatchArray2.length-1])
                noMatchArray2.push(val);
        }


    }

    console.log("matching elements: "+matchingElements);
    console.log("noMatchArray1: "+noMatchArray1);
    console.log("noMatchArray2: "+noMatchArray2);

}

}

Output:

matching elements: 1,4,6 noMatchArray1: 0,1,3,8,10 noMatchArray2: -3,-4,2,5,25,26

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

Scraping dynamic content with Python for websites using JavaScript-generated elements

Seeking assistance in using Python3 to fetch the Bibtex citation produced by . The URLs follow a predictable pattern, enabling the script to determine the URL without requiring interaction with the webpage. Attempts have been made using Selenium, bs4, amon ...

Angular UI modal on close event

Is there a way to trigger a function after a modal window is closed, regardless of whether it was closed by a button click or clicking on the backdrop? var dialog, options; options = { windowClass: "lightBox" templateUrl: "url to the template", con ...

Including variables in package.jsonORInjecting variables into package

I'm currently developing a React application and I am trying to figure out how to pass a variable from the .env file into package.json: {"proxy": "ENV_VAR"} Is there a way to achieve this? In addition, our app is built using Docker. Is it possible ...

Utilizing jQuery with variable assignment: A beginner's guide

Struggling to utilize a variable in jQuery? In the script snippet below, I set a variable "divname" with a value, but when using jQuery for fading out, it doesn't work as expected. What I really want is for the description to fade in when hovering ove ...

What methods and applications are available for utilizing the AbortController feature within Next.js?

My search application provides real-time suggestions as users type in the search box. I utilize 'fetch' to retrieve these suggestions from an API with each character input by the user. However, there is a challenge when users quickly complete the ...

Merging object keys and values from JSON arrays based on their keys, using JavaScript

Is there a way to merge object keys' values from JSON arrays based on their key? json1 = [ {key:'xyz', value:['a','b']}, {key:'pqrs', value:['x','y']} ] json2 = ...

Tips for accessing the 'styled' function in Material UI ReactHow to utilize the 'styled' function

Hey there, I'm facing an issue while trying to export a styled AppBar. Check out my code below: import * as React from 'react'; import { styled, useTheme } from '@mui/material/styles'; import MuiAppBar from '@mui/material/AppB ...

How can I extract an integer and match it to a corresponding name within JSON data using parsing?

Struggling to find a solution for my election system project. Currently working on parsing JSON Data to display election results based on the input. The issue lies in matching candidate IDs to their names in Python to register votes accurately. If you hav ...

JQuery Anchor Link Scrolling Problem on Specific Devices

I'm having an issue where my webpage does not scroll correctly to an anchor when a link is clicked. The problem arises from the header size changing based on the viewport width. While it works fine in desktop Chrome, in the mobile version the header h ...

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...

Struggling to retrieve the most recent emitted value from another component in Angular?

Hello everyone, I am currently attempting to retrieve the most recent updated value of a variable from the component app-confirm-bottom-sheet in the app-bene-verification.ts component, but unfortunately, I am unable to achieve this. Below is the code snipp ...

"Utilizing a function from an external file within the Main App function - a step-by-step guide

I am currently learning React.js and I have come across a challenge that I'm unable to solve easily. I am trying to use functions instead of classes in my code, but I am struggling with using these functions as components within my Main function. Here ...

Obtain the value of a checkbox using jQuery

Here is an example of dynamic checkboxes: <input type="checkbox" checked="checked" value="1" name="user_mail_check[]" class="ami"> <input type="checkbox" checked="checked" value="2" name="user_mail_check[]" class="ami"> <input type="checkbo ...

Unable to switch. Is there an issue with the initialization of Bootstrap 5 JavaScript?

I seem to be encountering an issue with my implementation of Bootstrap 5.0.0-beta2. While I can expand my navbars and accordions successfully, collapsing them does not work as expected. It appears that the problem lies in the initialization of the JavaScr ...

How about wrapping a large amount of text three times and including a "read more" link?

I am tasked with creating an HTML element that automatically detects when text has wrapped three times, truncates the content, and adds a "more..." link at the end of the third line. Can this be achieved? If yes, what is the process to implement it? ...

Adjust Mui Autocomplete value selection in real-time

I have implemented Mui AutoComplete as a select option in my Formik Form. <Autocomplete disablePortal options={vendors} getOptionLabel={(option) => option.vendor_company} onChange={(e, value) => {setFieldValue("vendor_id", value. ...