0

I want get closest number in the array. It have to be like this:
For example I have an array: [1, 3, 7, 15, 40, 55, 70, 80, 95]

Number variable: numberD1;
If numberD1: 8 - The closest number can be only 7. Not 15.
If numberD1: 54 - It can be only 40. Not 55.

I mean, i want closest number like this. But what I selected the number mustn't be higher than the closest number(like Math.floor() function).

Sorry for my Bad English. I hope i told my problem as good.

shershen
  • 9,875
  • 11
  • 39
  • 60
  • 2
    What have you done to try and solve this yourself? – Mike Cluck May 13 '16 at 22:03
  • check array forEach function, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – shershen May 13 '16 at 22:05
  • I using this function. And i found this on stackoverflow. `function closest(num, arr) { var mid; var lo = 0; var hi = arr.length - 1; while (hi - lo > 1) { mid = Math.floor((lo + hi) / 2); if (arr[mid] < num) { lo = mid; } else { hi = mid; } } if (num - arr[lo] <= arr[hi] - num) { return arr[lo]; } return arr[hi]; }` – Recep Selim Ağırman May 13 '16 at 22:05
  • Possible duplicate of [get closest number out of array](http://stackoverflow.com/questions/8584902/get-closest-number-out-of-array) – PeterKA May 13 '16 at 22:14

5 Answers5

1

You could use this:

// sample array
a = [1, 3, 7, 15, 40, 55, 70, 80, 95]

// get right number
function getClosest(a, numberD1) {
    return numberD1 - a.reduce(function(closest, v) {
        return numberD1 >= v ? Math.min(numberD1-v, closest) : closest;
    }, 1e100);
}  


// output result
document.write(8 + ' => ' + getClosest(a, 8));

document.write('<br>');

document.write(54 + ' => ' + getClosest(a, 54));
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Oh, i forgot say that. numberD1 can be float value. I tried numberD1 as float. Your function returned "-1e+100". Is this function only for integer values? – Recep Selim Ağırman May 13 '16 at 22:24
1

If I understood it correctly, you're looking for something like this, if the array is sorted:

var list = ...
var numberD1 = ...
var result = null;
for (var i = 0; i < list.length(); i++){
    if (list[i] <= numberD1)
        numberD1 = list[i];
}
return result;
Stefan K
  • 21
  • 5
0

Assuming your array is sorted, I would think in theory you could just do a search for the specified value, then return the value preceding it?

Iterate through with a search, then return numberD1[key - 1];

Ah, I just saw you are searching for any arbitrary value, I'm sure you can still figure out a way around that. Just search for the closest value above it then do what I showed.

Kronus
  • 13
  • 2
  • 9
  • That array keys, can be random numbers. Example [5,98,2]. So it be irregular. I use closest function as that but i want what closest number higher than numberD1 . Function: ` function closest(num, arr) { var mid; var lo = 0; var hi = arr.length - 1; while (hi - lo > 1) { mid = Math.floor((lo + hi) / 2); if (arr[mid] < num) { lo = mid; } else { hi = mid; } } if (num - arr[lo] <= arr[hi] - num) { return arr[lo]; } return arr[hi]; } ` – Recep Selim Ağırman May 13 '16 at 22:08
0

I just wanted to invent Array.prototype.insert() which inserts a series of items starting from the given index value and returns the mutated array. It is needed for functional JS. However the insertNum function subject to this question does not mutate the original array.

Array.prototype.insert = function(i,...rest) {
  this.splice(i,0,...rest)
  return this
}

var arr = [1, 3, 7, 15, 40, 55, 70, 80, 95];
var insertNum = (a,n) => a.slice(0)
                          .insert(a.reduce((p,c,i) => {var d = Math.abs(n-c);
                                                       p[0] > d && (p[0] = d, p[1] = n > c ? i+1 : i);
                                                       return p} ,[Infinity,0])[1],n);

document.writeln("<pre>" + JSON.stringify(insertNum(arr,8)) + "</pre>");
document.writeln("<pre>" + JSON.stringify(insertNum(arr,54)) + "</pre>");
Redu
  • 25,060
  • 6
  • 56
  • 76
0

This should do the job:

EDIT - Took care of getting a number which is lower if possible

function closest(num, array){
var closest = Infinity
    for (var i = 0; i < array.length; i++)
        if (closest < num){
            if (array[i] < num && array[i] > closest)
                closest = array[i]
        }
        else if (array[i] < num || array[i] < closest)
            closest = array[i]
    return closest != Infinity? closest :null
}
Pierre Tassel
  • 436
  • 3
  • 9
  • This isn't be useful for my issue. Because closest number must be higher than numberD1. On that function, it can be higher, for example: var numberD1 = 5; var array = [1, 2, 6, 7]; The closest number must be 2. Not 6. – Recep Selim Ağırman May 13 '16 at 22:29
  • This function should work as you wish, and supports float numbers as well. Oh, seems it's too late :) – Pierre Tassel May 13 '16 at 22:45
  • No matter :) I found a function. It working with jQuery. `function closest(goal, theArray) { var closest = null; $.each(theArray, function () { if (this <= goal && (closest == null || (goal - this) < (goal - closest))) { closest = this; } }); return closest; } ` That working for me :) – Recep Selim Ağırman May 13 '16 at 22:52