Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays:

var a = [126, 619, 4192, 753, 901];
var b = [413, 628, 131, 3563, 19];

Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following function,

function findCloseElements(array1, array2, percentage)

where

findCloseElements(a, b, 5);

would result in

[126, 131], [619, 628]

Answer №1

In order to compare elements between two arrays, you will need to iterate through each element of array1 and check it against every element in array2. This process can be efficiently achieved using nested loops. The following code provides a potential solution:

function compareArrays(array1, array2, threshold) {
    var result = [];
    threshold /= 100;

    array1.forEach(function(itemA){
        var maxDifference = itemA * threshold;
        array2.forEach(function(itemB){         
            if(Math.abs(itemA - itemB) < maxDifference) {
                result.push([itemA, itemB]);
            }                   
        });
    });

    return result;
}

Answer №2

To find the intersections of two arrays, iterate through each item in both arrays and check if the second array item is within 1 ± the desired factor multiplied by the first array item.

function* findIntersections(arr1, arr2, factor=0) {
  factor /= 100;
  for(let item1 of arr1)
    for(let item2 of arr2)
      if(item2 <= item1*(1+factor) && item2 >= item1*(1-factor))
        yield [item1, item2];
}
var arr1 = [126, 619, 4192, 753, 901];
var arr2 = [413, 628, 131, 3563, 19];
console.log(...findIntersections(arr1, arr2, 5));

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

Unable to get PrependTo to remove itself when clicked

Below is a custom jQuery script I put together: $(function(){ $("a img").click(function() { $("<div id=\"overlay\"></div>").hide().prependTo("body").fadeIn(100); $("body").css({ ...

Create a JavaScript variable every few seconds and generate a JSON array of the variable whenever it is updated

My variable, which consists of random numbers generated by mathrandom every second, such as "14323121", needs to be saved to an array for the latest 10 updates. function EveryOneSec() { var numbers = Math.random(); // I want to create an array from th ...

VueJS - Vuefire - Unexpected Error: document.onSnapshot is not a valid function

I'm currently working on integrating Vuefire into my project. I have been following the instructions provided on the Vuefire website, but I am encountering an error. db.js: import firebase from 'firebase/app' import 'firebase/firestore ...

The directive code takes precedence over the controller code and is executed first

A custom directive has been implemented and is utilized as shown below: <div car-form car="car" on-submit="createCar(car)"></div> This directive is used on both the new and edit pages, each with its own controller. The EditCarController retri ...

Unable to establish connection between Router.post and AJAX

I am currently in the process of developing an application to convert temperatures. I have implemented a POST call in my temp.js class, which should trigger my ajax.js class to handle the data and perform calculations needed to generate the desired output. ...

Retrieve the names contained within TD elements using the console

I always enjoy experimenting with new things. Take a look at the https://lodash.com/docs/4.17.15 lodash documentation site where you'll find a menu on the left side featuring all available functions. Is there a way to extract the names of these functi ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

In JavaScript, the input box is set to automatically capitalize the first letter, but users have the ability

How can I automatically capitalize the first letter of a user's name input, but allow for overrides like in the case of names such as "de Salis"? I've read on Stack Overflow that CSS alone cannot achieve this with text-transform:capitalize;, so ...

The functionality of the Bootstrap 4 Carousel featuring multiple items is experiencing malfunctions

I'm encountering an issue with my Bootstrap 4 card carousel. When the next or prev buttons are clicked, there is a strange transition effect. Additionally, in the mobile version, the buttons do not work properly. It seems that when the card slides to ...

Comparing boolean values in React JS

I am working with a React JavaScript code in which I am iterating through a series of boolean values. The issue I am facing is that when 'data.nextrow' is false, I expect nextrow1 to also be false but it ends up being set to true instead. co ...

Progressive Web App (PWA) default start URL

I am currently facing an issue with my Vue app, which is also a Progressive Web App (PWA). While the PWA functions correctly as planned, I realized that I am using generic paths for my web application. This means that in order to access the correct page, ...

Error encountered when attempting to establish a connection between socket.io and express: network error

Similar Question: socket.io: Failed to load resource I'm having trouble getting a simple express + socket.io hello world app to work. I keep receiving the following error: "NetworkError: 404 Not Found - http:// localhost:3002/socket.io/socke ...

The content of a Puppeteer page mysteriously disappears when transferred to another function

My current project involves using Puppeteer for web scraping on my website. I encountered a strange issue where the await page.content() works fine when I console log the content, but turns out to be null when passed as an argument to another JavaScript ...

Leveraging async/await within a React functional component

Just getting started with React for a new project and facing challenges incorporating async/await functionality into one of my components. I've created an asynchronous function called fetchKey to retrieve an access key from an API served via AWS API ...

Navigating with jQuery Scrollbars

Looking to incorporate a bit of animation in jQuery, trying out the following line: window.parent.scroll(coord[0], coord[1]); The next block of code doesn't seem to be achieving what I had in mind. Do you have any suggestions? $(window.parent).anim ...

The RSS feed is stretching beyond the limits of the table's height

Seeking assistance to adjust the height of an RSS feed widget on my website. The widget is from RSS Dog and I do not have access to the style.css file as it is hosted externally. Despite trying to modify the JavaScript code provided by RSS Dog to set the h ...

Having issues sorting the ranking table numerically in a Javascript/jQuery/JSON/localStorage game

I have successfully created a leaderboard for my game, but I am struggling to automatically sort the scores from high to low. I believe that placing the objects into an array and then sorting them may be the solution, however, I am unsure of how to do th ...

Problem with Bootstrap multiselect: it only opens the first time, and stops working after an ajax call

I am having trouble using Bootstrap multiselect with jQuery ajax. When I run the ajax code, the multiselect button stops working properly. To see the issue in action, click here: and look at the last multiselect dropdown. Here is the ajax code snippet: ...

Alter the design when hovering over a relevant element

How can I change hover styles for specific items in React? Currently, all item styles change at once when hovered. I want to only change the style of the selected div when hovering over the add to cart button. Visit this link import React, { useState } fr ...

What is the process for retrieving the JSON element?

@Override protected void onPostExecute(String response) { String firstName = null; String lastName = null; try { JSONObject jsonResponse = new JSONObject(response); JSONArray jsonArray = jsonResponse.getJ ...