Reputation: 3
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.
Upvotes: 0
Views: 1836
Reputation: 26161
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>");
Upvotes: 0
Reputation: 446
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
}
Upvotes: 0
Reputation: 349954
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));
Upvotes: 1
Reputation: 31
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;
Upvotes: 1
Reputation: 13
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.
Upvotes: 0