closest number, based on two numbers

Im currently checking what the closest number would be compared to an array:

var testarray1 = [4054,4938,4983,1928,8833];
var test = 5000;

var result = testarray1.reduce(function(prev, curr) {
  return (Math.abs(curr - postcode) < Math.abs(prev - postcode) ? curr : prev);
  }

This works fine.

but when i have it like multi numbers in one, it dosent work:

var testarray1 = ["4000-5595","4400-4720"];
var test = 4630;

for (var x =0; x < testarray1.length; x++) {
      var selectedPostcode = testarray1[x][0];
      var splitted = selectedPostcode.split("-");
      var from = parseInt(splitted[0]);
      var to = parseInt(splitted[1]);
      if (postcode >= from && postcode <= to) {
        return selectedPostcode;
        break;
      }
    }

in the example code above, it would return "4000-5595", but how can i do so it selects the closest one, in this case it would be the "4400-4720"?

47 thoughts on “closest number, based on two numbers”

Leave a Comment