Algorithm in Javascript that identifies the larger number that matches the given input

I recently encountered a logic problem that involved comparing an input variable with an array to find the smallest number in the array without using sorting. For example, I had an array like:

const arr = [20,25,13,10,3,5,9,22];

and an input value of:

var inputt = 3;

The task was to identify the smallest number in the array that is greater than the given input. In this case, the expected answer would be "5".

I experimented with looping through the array to find the smallest number but struggled to determine how to specifically find the smallest number in the array that is greater than the input.

var myarr = [5,3,9,10,7];
var smallest = arr[0];

for(var i=1; i<arr.length; i++){
    if(myarr[i] < smallest){
        smallest = myarr[i];   
    }
}

console.log(smallest);

Answer №1

const numbers = [20,25,13,10,3,5,9,22];
const userInput = 3;
const result = Math.min(...numbers.filter(num => num > userInput));

console.log(result)

Remove any numbers that are lower than the user input, then determine the smallest among them.

Answer №2

Give this a try and keep me posted on the outcome

let myArray = [5, 3, 9, 10, 7];
let smallestNum = myArray[0];

for(let i = 1; i < myArray.length; i++){
    if(myArray[i] < smallestNum){
        if(myArray[i] > userInput){
             smallestNum = myArray[i];  
        }
    }
}

console.log(smallestNum);

Answer №3

To find a matching number, try using the reduce method which will return undefined if no match is found.

const result = arr.reduce((accumulator, value) => (value > input && (accumulator === undefined || value < accumulator)) ? value : accumulator, undefined);

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

Looking for guidance on where to find a functional code sample or comprehensive tutorial on working with ViewMetadata in Angular2

I am currently trying to understand the relationship between viewmetadata and the fundamental use of encapsulation: ViewEncapsulation, including ViewEncapsulation.Emulated and ViewEncapsulation.None. Here is a link for further information: https://angula ...

The callback function for the `input` component in React Native must be a function and should not be undefined. Always remember to start component names with the proper syntax

There was a gap in my project as I have an application currently under development for testing purposes. Error: The view config getter callback for the component input must be a function (received undefined). Make sure to capitalize component names. I am ...

There was an unhandled type error stating that "undefiened" is not a function while processing a JSON

Hey there! I'm currently using JSON to send a list of songs to populate my table. The JSON response is working fine up until the controller URL. However, when I attempt to loop through it and display the details in my table, I encounter an error. $( ...

Launching a program through a web browser - a step-by-step guide

I am looking to create a specific sequence of events: A web browser opens, and a user logs in (the exact action is not crucial) The user is then redirected to a new page where another program should automatically open This process is similar to what happ ...

What is the process of attaching data to a mat form field in Angular?

How can I show the data from an http request on a form field in Angular? I want the user to be able to edit the data and submit it. The email, firstname, etc. should display in the input fields. When the edit button is clicked, I want the form field value ...

What is the best way to perform a pure JavaScript forEach loop and display the output with Firebase?

I am attempting to retrieve data from a firebase database and display all of the results. I am used to using jquery's appendTo function for this task, but I am unsure how to achieve the same result with pure javascript. Below is my current script: & ...

Send the typeahead object result from Angular to another function within the controller

In my current setup, I am utilizing the ui-bootstrap typeahead feature to fetch an object from an external API. Upon selecting the object, it triggers a callback function that stores the results in a separate function within my controller. The challenge l ...

I am seeking a lambda expression that can demonstrate the concept of the Fibonacci Sequence

Stream.iterate(new Long[] {0L, 1L}, p -> new Long[] {p[1], p[0]+p[1]}).map(p -> p[0]); Could someone clarify the thought process behind this lambda expression? I'm attempting to mentally troubleshoot the Fibonacci Sequence in a lambda expressi ...

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

I keep receiving multiple header errors from ExpressJS even though I am positive that I am only sending a single header

Can someone please help with the issue I'm facing in the code below: router.put("/:_id", async (req: Request, res: Response) => { try { // Create the updated artist variable const artist: IArtist = req.body; const updatedArt ...

Exploring the capabilities of mongojs: Adding items to arrays within fields

I've been researching extensively on this subject, but I'm completely stumped. Here's my dilemma (I'm working with node.js and mongojs): I want to create documents like the following: { "_id" : ObjectId("50ce2f7f98fa09b20d000001" ...

Is there a way to show information exclusively on the selected card upon clicking?

[click here to see image 1] https://i.sstatic.net/cfvUT.png [click here to see image 2] https://i.sstatic.net/ISXAU.png Greetings, fellow beginners! Once again I find myself stuck on a coding problem. I have fetched various workout data and displayed t ...

Using setAttribute will convert the attribute name to lowercase

When creating elements, I use the following code: var l = document.createElement("label");. I then assign attributes with l.setAttribute("formControlName","e");. However, a problem arises where the setAttribute method converts formControlName to lowercase ...

The repeated execution of a Switch Statement

Once again, I find myself facing a puzzling problem... Despite making progress in my game, revisiting one aspect reveals a quirk. There's a check to verify if the player possesses potions, and if so, attempts to use it involves calculating whether the ...

JavaScript code utilizing Selenium to retrieve text from a Tinymce text editor

When using https://ocr.sanskritdictionary.com/ to upload an image, the copyable text appears in a Tinymce editor. I am looking for suggestions on how to copy the resulting text using Selenium JavaScript code. I have attempted to extract it using the html ...

Tips for centering the InputLabel in Material UI?

Upon loading the page, I am looking to have the InputLabel appear as shown in the second picture. However, I haven't been able to find any InputLabel props that achieve this. I attempted using the focused prop, but it didn't give me the desired o ...

Securing Angular 2+: Safeguarding Server-Side Lazy Loaded Modules

In my Angular 2+ application, users input personal data that is then analyzed in a different section of the app restricted to authorized personnel. The challenge lies in preventing unauthorized individuals from gaining insight into the analysis process. We ...

Tips for resolving the "Unexpected reserved word" error during the installation of Laravel Jetstream

I have been following the steps outlined on to set up Laravel Jetstream. Upon running artisan jetstream:install, I selected Livewire support, API support, email verification, and PHPUnit support for installation. Next, I executed npm install as per the ...

Exploring methods to extract specific attributes from an array of objects stored in JSON format

I am working with an array of JSON objects. arr = [{'a'=> 1, 'b'=> 2, 'c'=> 3}, {'a'=> 4, 'b'=> 5,'c'=> 6}, {'a'=> 4, 'b'=> 5,'c'=> 6}] ...

Eliminate the final two digits from each element in the array if they exceed two digits

A challenge I am facing involves an array with multiple elements. My goal is to remove the last two digits from any element in the array that consists of 3 or 4 digits, while leaving elements with 1 or 2 digits unchanged. var test =[ 2, 45,567, 3, 6754]; ...