Ad

JS, Get The Closest Previous Number From Array

- 1 answer

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);
}
Ad

Answer

You could find it by looking to the next value of the array.

function getSmaller(value, array) {
    return array.find((v, i, { [i + 1]: next }) => v === value || next > value);
}

console.log(getSmaller(400, [100, 250, 500, 1000, 5000]));  //  250
console.log(getSmaller(500, [100, 250, 500, 1000, 5000]));  //  500
console.log(getSmaller(5000, [100, 250, 500, 1000, 5000])); // 5000

For all smaller values, you could change the condition.

function getSmaller(value, array) {
    return array.find((_, i, { [i + 1]: next }) => next >= value);
}

console.log(getSmaller(400, [100, 250, 500, 1000, 5000]));  //  250
console.log(getSmaller(500, [100, 250, 500, 1000, 5000]));  //  250
console.log(getSmaller(5000, [100, 250, 500, 1000, 5000])); // 1000

Ad
source: stackoverflow.com
Ad