Find a specific number within an array using Javascript, and if it is not found, return the closest

In Javascript, I want to find a number in an array. If the number does not exist in the array, I need to return a number that is lower than the target number.

Answer №1

This unique function is designed to locate the largest array element that is equal to or slightly less than the specified value. In simple terms, if the specified value exists in the array, it will be returned. If not, the function will return the largest value in the array that is still smaller than the target value. To put it another way, you will receive the largest value that is not greater than the target value.

Upon execution, the function will provide both the value and the position (index) of the identified element in the array. While there may be multiple elements with the same value in the array, the function will return the index of the first occurrence.

function getBiggestElementNoBiggerThan(arr, x) { // Search for element x in Array arr.
    if (arr.length == 0) {                        // The array must not be empty,
        return null;                              //  otherwise the result is null.
    }
    var best = { value: arr[0], index: 0 },       // Start with the first element.
        n = arr.length;
    for (var i = 1; i < n; ++i) {                 // Check the rest of the elements.
        if (arr[i] == x) {                        // Have we found the desired value?
            return { value: x, index: i };
        } else if (arr[i] > x) {                  // If not, is this better than our current best?
            best = { value: arr[i], index: i };   //  Take note that if multiple values are equally good,
        }                                           //  the index of the earliest one is selected.
    }
    return best;                                  // Return the best value found.
}

function test(arr, x) {
  var result = getBiggestElementNoBiggerThan(arr, x);
  document.write('the largest element in '+arr.join(', ')+' that is not less than '+
                 x+' is: '+result.value+' at index '+result.index+'<br />');
}
document.write('Test cases: <br />');
test([3, 1, 4, 1, 5, 9], 1);
test([3, 1, 4, 1, 5, 9], 5);
test([3, 1, 4, 1, 5, 9], 8);

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

The concept of a callback function is not applicable within the context of MongoDB in Node.js

I am encountering an issue while validating the existence of an email or username in my MongoDB users collection within Node.js using my User Model. Whenever I attempt to perform this validation, I receive an error stating callback is not a function. This ...

Marionette - Apply a class to the parent ItemView's tagname

I've been working with Bootstrap accordion panels and I'm trying to assign a class to the parent panel of the panel-collapse. Essentially, what I want to achieve is: if (child element) hasClass('panel-collapse.in') { this.addClass ...

display the hidden box contents when clicking the button within a PHP loop

I am attempting to create a simple e-commerce site for learning purposes, but I encountered an issue when trying to display information upon clicking a button. The button does not seem to trigger any action as expected. It is meant to reveal text from the ...

Initiate the countdown when the button is pushed

Recently ran into an issue where a button triggers a command to a Perl script, causing the page to continuously load for 60 seconds. To provide users with transparency on when the Perl script will be finished running, I implemented a JavaScript countdown t ...

Enable/Deactivate Chrome Extension Content Script

I am exploring ways to enable users to toggle a Chrome content script with the click of a button. It appears that using chrome.browserAction is the most efficient method for achieving this. However, when I include the following code snippet: chrome.brow ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

Double-click to toggle with jQuery

Here is the code for my toggle menu: $(function () { $('#menu li').click(function () { $('#menu li').removeClass("active"); $(this).toggleClass("active"); }); }) It works perfectly, but there is one issue. When ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...

Stop Scrolling in VueJS

I am currently facing a challenge in preventing scrolling only when the lightbox component is open. I prefer not to rely on any external libraries or plugins for this task. Within my App.vue file, I have included the "LightBox" component. Therefore, it se ...

Error in Discord Bot: discord.js showing TypeError when trying to read the length of an undefined property

I'm currently working on developing a Discord bot and using CodeLyon's Permissions V2 video as a guide for reference. There seems to be an issue in my message.js file which contains the following code: require('dotenv').config(); //cre ...

Challenges with v-autocomplete in Vuetify.js

I am currently working with the v-autocomplete component and finding it somewhat rigid in terms of customization. I am hoping someone can provide some insight on this issue. Is there a way to have a default display text value in the input when the page fi ...

Update the HighChart Pie chart depending on the selection in the dropdown menu

Currently, I am working on creating a pie chart using data retrieved from a web socket in JSON format. Once the JSON object is returned, if the user selects the "Pie Chart" option, another Select dropdown will be displayed to choose a specific time period. ...

How can one get rid of a sudden strong beginning?

Recently, I delved into the world of CSS animation and encountered a frustrating issue. I've tried numerous methods and workarounds to achieve a smoothly looping animation without interruptions. Despite my efforts, I have not been able to replicate th ...

Arrows indicating the direction of a LineString feature in Openlayers 4

I'm attempting to create a LineString with arrows at the end of each line to indicate the direction of the route. I found an example on the official site: The example code in the link creates arrows through user drawing, but I need arrows for a give ...

What could be causing jQuery document ready to restrict access to global variables?

Currently, I am working on a project that involves three separate JavaScript files (example1.js, example2.js, and example3.js) being scripted into a single HTML file (index.html). These JS files are responsible for making an API call and manipulating the r ...

What is the best way to ensure that the state is updated only when the user begins typing in a text

I am currently working on a text editor-related code and my main focus is to update the state of the editor only when the user starts typing in the editor. The state should be updated under the following scenarios: 1. Update the state when the user begin ...

What causes npm start to fail with a CORS error, but run successfully with HOST=127.0.0.1 npm start?

Currently, I am in the process of creating a basic application that utilizes Flask for the backend and React for the frontend. An issue arises when attempting to initiate my React application through npm start, as it triggers a CORS error. Strangely enough ...

searchkit - Issue with Maintaining State of RefinementListFilter Checkboxes

I was curious about the functionality of the RefinementListFilter in searchkit. I have multiple filters that are boolean values, such as {field: 'hasChildren': {'1' : 'Yes', '0': 'No'}} to illustrate the tr ...

How the React Component Class Executes OnChange Event in a Closure

When working on my React code, I found myself creating a closure by calling "onChange." class CityInput extends React.Component { constructor( props ){ super( props ); this.state = { city : "", country : "" ...