Get the closest next or previous integer in a sorted array of integers

// array = sorted array of integers
// val = pivot element
// dir = boolean, if true, returns the previous value

function getVal(array, val, dir) {
  for (var i=0; i < array.length; i++) {
    if (dir == true) {
      if (array[i] > val){
        return array[i-1] || 0;
      }
    } else {
      if (array[i] >= val) {
        return array[i];
      }
    }
  }
}

Example:

array = [0, 5, 7, 9, 22, 27];
pivot = 11;

getVal(array, pivot);        //returns 22
getVal(array, pivot, true);  //returns 9

Comments

  1. written by: Calin on November 28, 2014 at 9:09 pm - Reply

    You can also use array.reduce to find the closest number. The only problem is that array.reduce doesn’t pass extra parameters to the callback, and you need to pass the “pivot”.

    To go around this problem, you could create a class, and store the “pivot” in the instance as a property.

    Here is a quick fiddle.

    Also, the array doesn’t have to be sorted for this implementation.

    • written by: Mihai on November 30, 2014 at 7:24 pm - Reply

      Thank you for your thoughts and for the fiddle. It’s a very nice method.

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 75 = 77