Can a Javascript binary search only match on values greater or equal?

When searching, this code will find the closest match. Usually, the closest match's x value is smaller than the target.x.

Is there a way to find the closest match where match.x is greater than or equal to the target.x value and match.y is the nearest y value?

The data is organized in ascending order based on x and then y.

var data = [
    {"x": 750, "y": 750},
    {"x": 750, "y": 850},
    {"x": 1000, "y": 500},
    {"x": 1000, "y": 1000},
    {"x": 2000, "y": 2000},
    {"x": 3000,"y": 3000}
];

console.log("Test 800", findClosestMatchGreaterOrEqual({'x': 800,'y': 800}));
// TEST 800 {x: 750, y: 850}

console.log("Test 2300", findClosestMatchGreaterOrEqual({'x': 2300,'y': 2300}));
// TEST 2300 {x: 2000, y: 2000}

function findClosestMatchGreaterOrEqual(target) {
    var low = 0;
    var high = data.length - 1;
    var item = null;
    var lastItem = null;
    while (low <= high) {
        var mid = ((low + high) / 2) | 0;
        lastItem = item;
        item = data[mid];
        var compare = compareItems(item, target);
        if (compare > 0) high = mid - 1;
        else if (compare < 0) low = mid + 1;
        else return item;
    }
    if (Math.abs(lastItem.x - target.x) < Math.abs(item.x - target.x)) return lastItem;
    return item;
}

function compareItems(a, b) {
    if (a.x != b.x) return a.x - b.x;
    if (a.y != b.y) return a.y - b.y;
    return 0;
}

Answer №1

After analyzing the statement that mentions finding the closest match where the x value is greater than or equal to the target.x value and the y value is the closest, I have made modifications to your function in order to achieve the desired outcome.

var data = [
    {"x": 750, "y": 750},
    {"x": 750, "y": 850},
    {"x": 1000, "y": 500},
    {"x": 1000, "y": 1000},
    {"x": 2000, "y": 2000},
    {"x": 3000,"y": 3000}
];

function closest(target) {
    var arr = [];
    var result;

    for (var i=0; i<data.length; i++) {
        arr.push({index: i, diffy: Math.abs(target.y - data[i].y), diffx: Math.abs(target.x - data[i].x), x:data[i].x, y: data[i].y});
    }

    arr = arr.sort(function(a, b) {
        return parseFloat(a.diffy) - parseFloat(b.diffy);
    });

    for (var i=0; i<arr.length; i++) {
        if(arr[i].x >= target.x) {
            result = arr[i];
            break;
        }
    }

    console.log(arr);
    console.log(data[result.index]);
    alert(JSON.stringify(data[result.index]));
}

closest({"x": 1000, "y": 1600});

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

How can I use jQuery to set the text in a select element in HTML?

I have come across more examples of this, but unfortunately they do not seem to work. $(window).load(function () { $("#country").html('Please make a selection from the options below'); }); <select id="country"> <option value="None"> ...

Difficulty in updating Vue variable value following a request

Hello everyone, I am facing an issue regarding a variable value. Within the request, I am comparing each array value to see if there is a match and then updating the match variable to true if a match is found. However, the problem arises when the updated ...

Coloring weeks in fullcalendar's two-shift calendar

Can FullCalendar create a calendar with alternating colors for odd and even weeks? Visit the FullCalendar demos here For example, see image below: https://i.sstatic.net/D5qza.png ...

The problem of "undefined function appendTo" is causing issues

My jQuery code looks like this: $(function() { var productTextTemplate = $('#product-text-template').html(); var productTemplate = $('product-template').html(); var product = productTextTemplate.appendTo(productTemplate); a ...

When does node.js start parsing the command line input into process.argv?

My application collects user input from a source other than a command line interface, resulting in a string format. Typically, if this input was received through the command line, Node would automatically parse the arguments into an array stored at process ...

Tips for Maintaining Toastr Notifications on ASP MVC Even After Redirecting to Another Page

I am currently working on an ASP MVC 5 application and encountering an issue with displaying a Toast notification. The toast notification is supposed to appear after updating a user's information to confirm the success of the operation. However, it ...

Is it possible to determine the height of a div after it has been rendered using the .resize method?

In my current structure, <div id="A"> <div id="A1"> <div id="B1"></div> <div id="B2"></div> </div> <div id="A2"></div> </div> A2 and B2 contain tables, while B1 has 4 checkboxes. I&a ...

"Unveiling the mystery of ejs form submissions with undefined values

I'm facing a bit of difficulty and need some guidance. I am attempting to develop a URL shortener using Node, Express, and Ejs. However, I'm encountering an issue where my EJS form is sending undefined values. Below is the snippet of my EJS code ...

Angular: module instantiation unsuccessful

Just getting started with Angular and running into an issue where the module seems to be unavailable. https://docs.angularjs.org/error/$injector/nomod?p0=plopApp My code is very basic at the moment, just setting things up: @section scripts{ <script s ...

Hovering over objects in Three.js does not function as effectively as clicking on them

Just getting into Three.js I'm attempting to load a GLTF model and add mouseover and mouseout events. The goal is for the color of the GLTF model to change on mouseover and revert back to the original on mouseout. I have had some success with this, ...

Using an Ajax call within an event handler function

After spending a full day attempting to execute an AJAX call within an event handler function, I've tried various combinations of when(), then(), and done(), as well as setting async: false. However, I keep encountering undefined errors despite my eff ...

Combine the outcomes of various AJAX requests into one variable

Looking to make 2 recursive API calls to create a JQuery datatables page with data from the range of 2016-2021. The API responses are split based on year filters to bypass the 5000 item list limit set by Sharepoint Online. Struggling to combine all API re ...

The behavior of the Bootstrap toggle with a chevron varies between the production environment and the local

For my Bootstrap accordion menu, I used a trick where the chevron turns upside down when clicked on the toggle. You can check out the trick here. In the example, the chevron is pulled to the right. When I implemented this on my website locally, the chevr ...

I am unable to sketch my backdrop. - HTML Canvas Game

Recently I've encountered an issue in my code where the image doesn't appear and mouse interaction stops working when I uncomment bg.draw() within the draw function. function draw() { clearAllCtx(); player.draw(); ene ...

Tips for concealing an entire row of a table with Jquery

I am currently working on a system that involves a table with anchor tags named original and copy in each row. By clicking on these anchor tags, we are able to update the database whether the item is an original or a copy using ajax. However, I am facing a ...

Adjusting the transparency of numerous elements using JavaScript or jQuery

My task involves creating a large form where elements initially have an opacity of 0.5, and when a button is clicked, the opacity changes to 1.0. While I can achieve this using JavaScript, I want to find a more efficient way by avoiding individual if state ...

The hidden DIV containing an ASP.NET CheckBox consistently yields a value of false

I have a group of form elements located within a hidden div which looks like this: <div id="jDivUpdateFolder" style="display:none;"> <asp:TextBox ID="txtEditFolderName" runat="server"></asp:TextBox><br /> <asp:TextBox ID ...

Ensuring seamless user recognition when redirecting them to a new HTML page

In our web application, new users are assigned a standard password upon registration. Upon logging in with the standard password, they are automatically redirected to a 'change Password' page where they can update their password. However, we hav ...

The lua.vm.js ajax callbacks are triggering, but unfortunately, the requested data is not

After raising this issue at https://github.com/kripken/lua.vm.js/issues/5, I realized that submitting it to stackoverflow might yield a faster response due to higher exposure. To ensure clarity, I will restate my question: How can the callback data be acce ...

Node.js is throwing a JSON parsing error due to an unexpected end of input

Currently, I am attempting to analyze the JSON data that is returned using the following PHP code snippet; $UserData = $con->query("SELECT * FROM Discord WHERE RobloxID=".$UserId) or trigger_error($mysqli->error); $result = $UserData->fetch_a ...