Finding the largest number that is less than a specified variable within an array

I have a JavaScript array and a variable, set up like this;

var values = [0, 1200, 3260, 9430, 13220],
    targetValue = 4500;

How can I efficiently find the largest value in the array that is less than or equal to the given variable?

In the provided example, the desired result would be 3260.

One approach could be like the following;

values.sort((a, b) => b - a);
let result = values.find(val => val <= targetValue);

However, it's important to consider cases where the selected value is the last one in the array. Additionally, the solution should be concise for such a simple task.

Is there a more efficient way to achieve this without unnecessary verbosity?

(and yes, using a jQuery loop here was not ideal, but it serves as a simplified example)

Answer №1

If you want to achieve the same outcome in a more elegant way, consider using a combination of array filtering and apply(). This method provides a cleaner and easier-to-read solution. By utilizing filter(), you can extract elements from array 'a' that do not meet the condition specified by the predicate function. Then, by employing apply(), Math.max is called with each extracted element as an argument.

let a = [1, 2, 3, 4, 5];
let b = 4;
let result = Math.max.apply(Math, a.filter(function(x){return x <= b}));

The resulting value will be 4.

Answer №2

let maximumValue = Number.MIN_VALUE;
for (let index = 0; index < array.length; index++) { 
  if (array[index] <= limit && array[index] > maximumValue) { 
    maximumValue = array[index]; 
  } 
}

In my opinion, the method mentioned above is straightforward, easy to understand, and not overly wordy. Another approach would be to utilize the reduce function, like this:

let maxVal = array.reduce(function (previousValue, currentValue) { return currentValue <= limit ? Math.max(previousValue, currentValue) : previousValue }, Number.MIN_VALUE);

Answer №3

Using the grep() function in jQuery

 var numbers = [10, 200, 560, 980, 1220],
 target = 300; 
 var result= Math.max.apply( Math,$.grep(numbers,function(num){return num<=target}));
 document.write(result)

SEE IT IN ACTION

Answer №4

Is there always a sorted array? If that's the case, you may be able to optimize your code in this way (make sure to verify the indexes, as I have not done so):

let start = 0;
let finish = arr.length;
while ((finish - start) > 1) {
    let currentIdx = Math.floor((start + finish) / 2);;
    if (arr[currentIdx] < target) {
        start = currentIdx;
    } else if (arr[currentIdx] > target){
        finish = currentIdx;
    } else {
        start = finish = currentIdx;
    }
}
let maximum = arr[start];

Answer №5

let nearestValue = null;
$.each(arrayData, function() {
    if (nearestValue == null || Math.abs(this - target) < Math.abs(nearestValue - target)) {
        nearestValue = this;
    }
});

A jQuery alternative in case it is needed.

Answer №6

To achieve the desired outcome, you can use the following function:

function findMaximum(arr, maxValue){
  var result;
  for(var index = 0, length=arr.length; index<length; index++){
    if(arr[index] <= maxValue) result=arr[index];
    else return result;
  }
  return false;
}

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

Issue with server-side rendering due to importing routes

After researching SSR with React, I came across various approaches but found one example that seems more suitable for my web app built on React/GraphQL/Apollo/Express/Webpack. However, I am facing an issue. Here are some code snippets: server.js ... ...

Engaging JavaScript Navigation

I am looking to create an interactive JavaScript menu or image map where users can press down, highlight, and hit enter on four different items to reveal hidden messages. However, I struggle with JavaScript and could really use some assistance. I have alr ...

Achieving CSS transition effects using the .appendChild function in JavaScript

When using the mouseenter event, I have a JavaScript function applied to an svg path element: const fadeIn = (event, locale) => { event.target.style.fill = 'hwb(' + (120 - score[locale] * 1.2) + ' 0% 0% / 1)' } This function wor ...

Relay information between requests using a RESTful API and various data formats, such as JSON, XML, HTML

In a scenario with a REST API that can deliver JSON, XML, HTML, and other formats, the default response for browsers without JavaScript enabled is HTML. This API utilizes tokens for authentication and authorization. Within a traditional website project, t ...

Fixed positioning upon scrolling begins prior to reaching the uppermost point (top div)

Currently, I have implemented a feature where #filter (the white select list in my sidebar) becomes fixed when it reaches the top of the page and stays there while scrolling until it reaches the footer and is released. However, I encountered an issue wit ...

AngularJS Resource GET Request Unsuccessful

Is there a way to verify if a resource failed to be fetched in AngularJS? For instance: //this is valid syntax $scope.word = Word.get({ id : $routeParams.id },function() { //this is valid, but won't be triggered if the HTTP response is 404 or an ...

Displaying JSON data in HTML proves to be a challenge

I have collected JSON data and organized it into two arrays, then displayed it in JSON format. Now I'm trying to showcase this data in HTML using two loops by correlating the IDs of one array with the userIds of another array. {"personaldetails":[{"i ...

What is the best way to hide the div when scrolling to the top?

Is there a way to hide the circle once it's scrolled to the top? Currently, I can scroll the circle to the top but it remains visible. Upon further exploration, I found that clicking on the circle scrolls it to the top and then on a second click, it f ...

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

Troubleshooting: Vue Component Unable to Locate Property

Just dipping my toes into Vue with a simple test implementation and running into some trouble breaking down data into components. Let's take a closer look at the code: <body> <header id="main-header"> <custom-header></ ...

What distinguishes v-text from v-load in Vue.js when concealing {{ Mustache }}?

When experiencing the "flash of uncompiled content" in Vue, the brief moment when the page is loading and you see the {{ Mustache }} syntax, developers often use either v-text or v-cloak. According to the documentation, v-text: Updates the element’s t ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

not getting any notifications from PHP

Despite receiving a status of '1' from this process file, my JavaScript code seems to be working fine. However, I am facing an issue with not receiving the email. <?php //Retrieve form data. //GET - user submitted data using AJAX //POST - in ...

Using an object method within a different object in JavaScript

I am attempting to create two objects, one from each of my classes - a Person object and a Drink object. I then want to invoke the drinking method by passing in a Drink object. However, I am struggling with how to do this. Here is my code, and I can't ...

notifying users via email in a React application with data saved in Firebase database

In order to notify users of upcoming deadlines, I need to send an email when they are approaching. The deadline is saved in Firebase as a specific date and time (mm/dd/yyyy mm: hh), associated with the user's account email address ([email protect ...

Having trouble retrieving elements from combined arrays

After being advised to merge 2 objects together, I used the array_merge function. However, I am now facing an issue where I can't access the second object from the merged result. The keys that appear after the merge process look strange. Have I made a ...

Setting up the Firebase emulator: should you use getFirestore() or getFirestore(firebaseApp)?

After delving into the process of connecting your app to the Firebase emulators like Firestore emulator, I came across the primary documentation which outlined the steps for Web version 9: import { getFirestore, connectFirestoreEmulator } from "fireba ...

Troubleshooting a problem with the Jquery Quicksearch plugin on constantly changing web

Quicksearch is pretty amazing... but it faces a usability issue that causes strange behavior. Many users hit enter after entering a search query, which reloads the page without any parameters and destroys the queries. Check this out: Adding: $('for ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Issue with AJAX POST request: PHP failing to establish session

I would like to pass the element's id to PHP and create a session for it. This snippet is from a PHP file: <?php $sql = "SELECT id FROM products"; $result = mysqli_query($con,$sql); while($row = mysqli_fetch_array($result)) { ?> <tr cl ...