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)