Find the nearest value in an array

I need to find the closest number in an array that is not higher than a specified number. Here's an example scenario:
Let's say we have an array:

[1, 3, 7, 15, 40, 55, 70, 80, 95]

The variable for the number is: numberD1;
If numberD1 is 8 - The closest number should be 7, not 15.
If numberD1 is 54 - The closest number should be 40, not 55.

In other words, I want to find the closest number in the array that is not greater than the selected number (similar to the Math.floor() function).

I apologize for any grammar errors in my English. I hope I have explained my issue clearly.

Answer №1

If you're looking for a solution, consider this code snippet:

// Here is a sample array for demonstration
let numbers = [1, 3, 7, 15, 40, 55, 70, 80, 95];

// Finding the closest number in the array
function getClosestNumber(numbers, target) {
    return target - numbers.reduce(function(currentClosest, value) {
        return target >= value ? Math.min(target - value, currentClosest) : currentClosest;
    }, 1e100);
}  

// Outputting the results
document.write('Closest number to 8 is: ' + getClosestNumber(numbers, 8));

document.write('<br>');

document.write('Closest number to 54 is: ' + getClosestNumber(numbers, 54));

Answer №2

Based on my understanding, it seems that you are in search of a solution similar to this one, especially when the array is organized in ascending order:

let myList = ...
let targetNumber = ...
let finalResult = null;
for (let index = 0; index < myList.length(); index++){
    if (myList[index] <= targetNumber)
        targetNumber = myList[index];
}
return finalResult;

Answer №3

If your array is already sorted, you can simply search for the specified value and return the value right before it.

Loop through the array with a search, then return numberD1[key - 1];

Oh, I see that you are looking for any random value, but I believe you can still find a solution. Look for the nearest value greater than it and apply the same logic I mentioned before.

Answer №4

Here is a solution that should meet the requirements:

Updated - Implemented logic to find a number that is closest but lower if possible

function findClosestLower(num, array){
var closest = Infinity
    for (var i = 0; i < array.length; i++)
        if (closest < num){
            if (array[i] < num && array[i] > closest)
                closest = array[i]
        }
        else if (array[i] < num || array[i] < closest)
            closest = array[i]
    return closest != Infinity? closest :null
}

Answer №5

I had this idea to create a custom method called Array.prototype.insert() that would add a series of items at a specified index in an array and return the updated array. This method is essential for functional JavaScript programming. However, the insertNum function mentioned in the context of this discussion does not alter the original array.

Array.prototype.insert = function(i,...rest) {
  this.splice(i,0,...rest)
  return this
}

var arr = [1, 3, 7, 15, 40, 55, 70, 80, 95];
var insertNum = (a,n) => a.slice(0)
                          .insert(a.reduce((p,c,i) => {var d = Math.abs(n-c);
                                                       p[0] > d && (p[0] = d, p[1] = n > c ? i+1 : i);
                                                       return p} ,[Infinity,0])[1],n);

document.writeln("<pre>" + JSON.stringify(insertNum(arr,8)) + "</pre>");
document.writeln("<pre>" + JSON.stringify(insertNum(arr,54)) + "</pre>");

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

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Leverage JSON data within an AngularJS controller

I have a JSON list in Angular that looks like this: vm.allnews = actualNews; After checking it with console.log, I can see that it's working fine and I am able to retrieve all news from the array list. Each news item has a title which I can display ...

Mastering the art of iterating through arrays using node.js request()

After transitioning from passing single values to multiple values in my node API, I encountered an issue where the API no longer responded. Here is an example of single values for fields: tracking: "123", // Only one tracking number carrier: "usps" // On ...

I've come across certain challenges when setting values for Vue data objects

I'm having trouble with a Vue assignment. Here is my code: new Vue({ el: "#alarmEchartBar", data: { regusterUrl: Ohttp + "historicalAlarmRecord/chart", regDistrictUrl: Ohttp + "district", regStreetUrl: Ohttp + "street/", regCameraUrl: ...

Why is it not performing as expected when removing all non-numeric elements from the array?

let arr = [1, "5", 3, 27, undefined, { name: 'Steven' }, 11]; for (let i = 0; i < arr.length; i++) { if (typeof arr[i] !== 'number') { arr.splice(i, 1); } } console.log(arr); // result: [1, 3, 27, {…}, 11 ...

Uploading an array to SQL Server and MySQL databases with C# .NET

In my Winforms application using C#, I am working with a List: List<string> StudentSubjects = new List<>(string); These are the subjects I have inserted into the List: StudentSubjects.Add("Physics", "Chemistry", "Mathematics", "English"); ...

Setting up xlsx for converting Excel spreadsheets to JSON format

Here is the command sequence I used to attempt the xlsx installation : sudo npm install xlsx npm install xlsx sudo npm install excel --save-dev npm install excel --save-dev However, after running each of these commands I encountered a consistent error mes ...

Why does Froala Editor not maintain formatting when retrieving data from the database?

I've been using the Froala editor to add content on my website, and it's doing well for inserting data into the database. However, I'm facing an issue when retrieving data from the database as it doesn't maintain the original formatting ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

Transfer files with Ajax without the need for a form tag or submission

I'm trying to send images via AJAX without submitting a form. Normally, when submitting a form I can access the images using $_FILES['images']['tmp_name']; However, when trying to send files, I receive an object FileList in an arra ...

Managing the ajax response to showcase a button within datatables

Here is my current datatable structure: <table id="list" class="display" width="100%" > <thead> <tr> <th>Title</th> <th>Description</th> <th>delete</th> ...

Activate JavaScript validation

Within each section (displayed as tabs), I have a custom validator. When one tab is active, the other is hidden. To proceed to submission, I need to disable client validation for the inactive tab. I attempt to do this by calling ValidatorEnable(, false); ...

Adjusting the value of 'this' within a service using a function

I am a newcomer to Angular and currently delving deeper into its intricacies. Despite my efforts in researching, I have not come across a solution for the issue at hand. My service sets the initial value of this.totalCount = 0; Within my controller, upo ...

Please indicate the number of lines for the href within the span element

I'm struggling with formatting a <span> tag, specifically the .lastMessageLink class that contains an <a> element with the .lastMessageText class. The content within .lastMessageText can vary from just a few characters to a lengthy paragra ...

Adjusting image dimensions dynamically using JavaScript based on screen size

My bootstrap setup seems to be causing issues when using the @media (min-height: 1000px) rule as the image class does not respond as expected. I am looking to implement a JavaScript solution that will automatically resize images once the screen height exc ...

Error: NextJS cannot access the 'map' property of an undefined object

Hey everyone, I usually don't ask for help here but I'm really struggling with this piece of code. I've tried looking at various resources online but can't seem to figure out why it's not working. Any guidance would be greatly appr ...

Auto Start Feature for jQuery Slider Function

Hey there, I currently have an image slider on my website that allows users to navigate through images by clicking on preview and next buttons. My query is: would it be possible to implement an auto start feature instead of having to click manually? Belo ...

What is the best way to showcase the chosen items from a treeview in ReactJS?

I'm struggling to figure out how to showcase the selected elements from my treeview. Any ideas or tips? The main purpose of this treeview is to filter data for export purposes. You can find the original code here. import React, {useEffect, useState} ...

Steps for removing a chosen file from several input files by clicking a button

Within my application, there is an input file that displays a list of selected files underneath it. Each of these selected files has a corresponding remove button. While I am able to successfully remove a single file with ease, I struggle when attempting t ...

Creating a script to open multiple URLs in HTML and JavaScript

Currently, I am working on creating a multiple URL opener using HTML and JavaScript. However, I have encountered an issue where HTTP links are opening fine but HTTPS links are not. Can someone provide assistance with this problem? Below is the code snippet ...