I need to retrieve the closest number from an array, however this number must always use the lower number from the array even if it is not the closest, I need to do this in plain JS, for example :-
Input = 499
Array = [100, 250, 500, 1000, 5000]
Answer = 250
Input = 900
Array = [100, 250, 500, 1000, 5000]
Answer = 500
EDIT: Ninas solution worked for fining the number however when used in my code I get error :-
Uncaught TypeError: Cannot destructure 'undefined' or 'null'.
Usage :-
var qtyBreaks = $("#SingleOptionSelector-0>option").map(function() {
if ($(this).val() != "sample"){
return parseInt($(this).val());
}
});
$('#Quantity-product-template').on('input', function() {
console.log(getSmaller($(this).val(), qtyBreaks));
// qtyBreaks = [100, 250, 500, 1000, 5000]
// $(this).val = 102 (always number)
});
function getSmaller(value, array) {
return array.find((v, i, { [i + 1]: next }) => v === value || next > value);
}
2
Answers
You can sort array in descending order (for this case you can use
Array.reverse()
) and find the first element (Array.find()
) which is less then or equal to input value.Hope this helps
You could find it by looking to the next value of the array.
For all smaller values, you could change the condition.