The question seems to be a bit weird. Never mind.
This is an array
[2, 7, 5, 10]
If I want to get the next greater number after 2, here's my code
var MyArray = [2, 7, 5, 10];
var RandomNumber = 2;
var MinGreaterThanPos;
for (var i =0; i < MyArray.length; i++) {
if (MyArray[i] <= RandomNumber)
continue;
if (typeof(MinGreaterThanPos) == 'undefined' || MyArray[i] < MinGreaterThanPos)
{
MinGreaterThanPos = i;
}
}
alert(MyArray[MinGreaterThanPos]);
It will return 7.
What if I want to get the lowest among the greater
numbers after 2?
That means, 7, 5, 10
are greater than 2. But I want to get 5, since the difference between 5 and 2 is lesser than any of the rest comparing with 2.
How will I do that?
Updated:
Coming to this point so far, what if there are objects inside an array?
For example:
var MyArray = [{user: 1, position:2}, {user:2, position: 6}, {user:3, position: 4}];
I want to do the same thing only with position
. If I choose position 2, then the next position I am hoping to get back is 4 and not 6.