简体   繁体   中英

JS, get the closest previous number from Array

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM