0

how can i search an number in array if the number not exists return lower than the target number in Javascript.

Chucky
  • 75
  • 1
  • 2
  • 10

1 Answers1

1

The following function finds the biggest array element that is no bigger than the desired value. In other words, if the desired value is found in the array, it will be returned. Otherwise, a smaller value will be returned, but this will be the biggest value that is smaller than the target value. Here is one more way to describe it: you will get back the biggest value that does not exceed the target.

The function returns an object containing a value and its index (position) in the array. There may be other elements in the array with the same value, but the returned index is that of the earliest element.

function getBiggestElementNoBiggerThan(arr, x) { // Seeking element x in Array arr.
    if (arr.length == 0) {                        // The array must be non-empty, or
        return null;                              //  else the result is null.
    }
    var best = { value: arr[0], index: 0 },       // Start with the first element.
        n = arr.length;
    for (var i = 1; i < n; ++i) {                 // Look at the remaining elements.
        if (arr[i] == x) {                        // Have we found the desired value?
            return { value: x, index: i };
        } else if (arr[i] > x) {                  // If not, is it better than our
            best = { value: arr[i], index: i };   //  current best? Note that if
        }                                         //  several values are equally
    }                                             //  good, we take the index of the
    return best;                                  //  earliest one.
}

function test(arr, x) {
  var result = getBiggestElementNoBiggerThan(arr, x);
  document.write('the biggest element in '+arr.join(', ')+' that is no less than '+
                 x+' is: '+result.value+' at index '+result.index+'<br />');
}
document.write('tests: <br />');
test([3, 1, 4, 1, 5, 9], 1);
test([3, 1, 4, 1, 5, 9], 5);
test([3, 1, 4, 1, 5, 9], 8);
Michael Laszlo
  • 12,009
  • 2
  • 29
  • 47