In JavaScript, locate the closest element in an array based on its value, avoiding cases where the value exceeds the nearest element

I am trying to find the nearest element in an array based on a given value, but I specifically want it to be the nearest one that is greater than or equal to the value. For example, if I have an array like [3000, 5000, 8000], when I search for a number below or equal to 3000, it should return 3000. However, if I search for 3001, it should return 5000 instead.

This is the code I currently have:

let array = [3000, 5000, 8000];

function closestNumArray(array, num) {
    var x = array.reduce(function(min, max) {
      return (Math.abs(max - num) < Math.abs(min - num) ? max : min);
    });

    return x;
}

closesNumArray(array, 3001) // returns 3000

I would like it to return 5000, or the nearest next element based on the value, but it currently returns 3000.

Thank you!

Answer №1

To find the closest number in a sorted array, a simple while loop can be used. If the loop reaches the end of the array (due to the value being too large), it will return the last value in the array.

let array = [3000, 5000, 8000];

const findClosestNumber = function(array, val) {
  let i = 0;
  while (i < array.length && array[i] < val) i++;
  return array[i] || array[i-1];
}

console.log(findClosestNumber(array, 2999));
console.log(findClosestNumber(array, 3000));
console.log(findClosestNumber(array, 3001));
console.log(findClosestNumber(array, 5000));
console.log(findClosestNumber(array, 5001));
console.log(findClosestNumber(array, 8000));
console.log(findClosestNumber(array, 8001));

Answer №2

Discovering the lower_bound of an element is what you need to do. This involves finding the position in a sorted array where your target element should be inserted.

let numbers = [3000, 5000, 8000];


numbers.sort();

console.log(numbers)

let goal = 3001;
let result = -1;
for(let i=0;i<numbers.length;i++){
if(goal<=numbers[i]){
result = i;
        break;
}
}

if(result == -1){
console.log("Element not found");
}
else{
console.log(numbers[result]); // -1 for when all elements are smaller than target
}

Answer №3

Finding the lowest element in O(log(n)) time complexity using binary search.

let numbers = [3000, 5000, 8000];

numbers.sort();

let key = 10000;

function findLowest(numbers, key){
    let low = 0, high = numbers.length;

    while(low < high){
        let mid = Math.floor((low+high)/2);

        if(key<=numbers[mid]){
            high = mid;
        }
        else{
            low = mid+1;
        }
    }
    return low;
}

let result = findLowest(numbers, key);
if(result == numbers.length){
    console.log('Element not found')
}
else{
    console.log(numbers[result]);
}

Answer №4

It is not necessary for the array to be sorted.

(function(array, num) { 
   return array.reduce(function(nearest, current) { 
                          return (Math.abs(current - num) < Math.abs(nearest - num))  
                                     ? current : nearest; 
                       }); 
})([3000, 5000, 8000], 4001)

The result is 5000 because 4001 is closer to 5000 than 3000.

The choice of naming the arguments in the reduce function as "min" and "max" might have led to confusion.

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 transfer all the formatting from the original file for the window.print() function. Localhost is functioning properly, but encountering issues with production

I'm encountering an issue with getting all styles from my Vue app. I have tried the code provided in this answer: https://stackoverflow.com/questions/52343006/how-to-print-a-part-of-a-vue-component-without-losing-the-style While it works fine on loc ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

Step-by-step guide on displaying a checkbox list based on the selected option in a drop-down menu

Apologies for the lackluster title. My goal is to create a dynamic checklist based on selections made from a drop-down menu: The drop-down menu offers several options, and when a choice is made, I want a corresponding checklist to appear below it with dep ...

Encountering issues with Next JS navigation when using the mobile back button

Recently, I put together a website using Next js 13 (with app router) and utilized Mantine UI for the front-end design. On mobile devices, I have implemented a responsive menu on the homepage. However, when I try to navigate back to the homepage from the ...

What are the steps to create a connect4 board featuring rounded corners and curved sides?

How can I create a Connect4 board with the exact styles and properties shown in the image? I want to achieve the curved sides effect as displayed. Can this be done using only HTML elements, or is there an easy SVG solution available? Here is my current co ...

Issue with Mjpg paparazzo.js functionality not functioning as expected

I am currently exploring alternative methods to view my security cameras without relying on browser support for mjpg streaming. I have come across Paparazzo.js, which appears to be a promising solution that I want to experiment with: https://github.com/rod ...

Merging two arrays by their corresponding IDs and indexes

Within my current project, I am working with two arrays. The first array, arr1, contains a questionID property that I need to use to combine it with arr2 based on the condition where arr1 questionID equals arr2 index. For example, if arr1 questionID is 1, ...

Error: The 'current' property is not defined and cannot be focused on

I have a total of 4 input fields, and I would like the user to automatically move to the next input field after filling out the current one. constructor(props) { ... this.textInput1 = React.createRef(); this.textInput2 = React.createRef(); ...

Creating a visually appealing label by customizing it according to the child div

Can the label be styled based on whether the input is checked or not using CSS, or do I have to use JavaScript? <label class="filterButton"> <input name="RunandDrive" type="checkbox" value="1"> </label> ...

To successfully use Router.use(), you must provide a valid middleware function. How can we resolve this issue of passing undefined as

I have developed a CRUD application using node.js and now I need to incorporate another node project as a microservice. To send HTTP requests to the other node project, I am utilizing the axios npm module. However, when I run the code, I keep encountering ...

Utilizing SASS, JavaScript, and HTML for seamless development with Browser Sync for live syncing and

I've been on a quest to find a solution that covers the following requirements: Convert SASS to CSS Post-process CSS Minify CSS Move it to a different location Bundle all Javascript into one file Create compatibility for older browsers Tre ...

Utilize vuex v-model to define the value of an object component

Coordinating input elements with object keys in Vuex state is my current challenge. Imagine I have this object: myObj: { foo: 1, bar: 2 } Within a component, I have a computed property set up like so: myObjVals: { get(){ return this.$store.state.myObj ...

Move the camera in Three.js along a path between two vectors

I created a basic scene and came across a tutorial at to help me move the camera: var timer = new Date().getTime() * 0.0005; camera.position.x = Math.floor(Math.cos( timer ) * 200); camera.position.z = Math.floor(Math.sin( timer ) * 200); However, I n ...

`Vue Router - Dynamically update route anchor on scroll`

My goal is to achieve the same routing behavior on my website as demonstrated here: https://router.vuejs.org/guide/#html. If you observe, the link changes to https://router.vuejs.org/guide/#javascript when you scroll down, and reverts when scrolling back u ...

I'm encountering a CastError while attempting to delete data in mongodb using Id

Encountered an issue while attempting to delete a MongoDB entry using the 'findByIdAndRemove' function in Mongoose. Specifically, it is throwing a 'Cast to ObjectId failed for value error'. Delete Service routes.delete('/:id' ...

Run a JavaScript function on a webpage loaded through an AJAX response

I need to trigger a function through an AJAX request sent from the server. The function itself is not located on the calling page. Here's an example of what I am trying to achieve: 1. PHP script being called: <script> function execute() { ...

Generating masks of different lengths using tensorflow

I'm trying to manipulate a tensor of lengths in TensorFlow, which looks like this: [4, 3, 5, 2] My goal is to generate a mask consisting of 1s and 0s, where the number of 1s corresponds to the values in this tensor, padded with 0s to a total length ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

Can you explain the concept of a TransientTransactionError within Mongoose (or MongoDB)?

Two important files in my project are server.js and db.js. The db.js file is responsible for interacting with the database using Mongoose, while server.js calls functions from db.js: var mongoose = require('mongoose'); mongoose.connect('&ap ...

Positioning the infowindow in Google Maps API v3

Creating a map with various markers, each with its own info window. However, when attempting to display an info window on multiple markers, the position remains fixed at the first clicked marker. What could be causing this issue? <script type="text/jav ...