skip to Main Content

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


  1. 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

    var input1 = 499
    var array1 = [100, 250, 500, 1000, 5000]
    
    var input2 = 900
    var array2 = [100, 250, 500, 1000, 5000]
    
    
    var output1 = array1.reverse().find(item => item <= input1);
    
    console.log('Output 1: ', output1);
    
    var output2 = array2.reverse().find(item => item <= input2);
    
    console.log('Output 2: ', output2);
    Login or Signup to reply.
  2. 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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search