0

i am having one collection . The collection is below

X=[1940,1941,1943,1945,1978]

i want to find the nearest values from the above collection by passing some value (ex:1944.578895)

for 1944.57889 it will return 1945 and for 1943.5 it will return 1943 like that. the collection "X" will be varied that means it contains floating numbers too.

so i want to find the nearest value for floating point collection as well numeric collection.

Thanks,

Siva

Ahmad Azwar Anas
  • 1,289
  • 13
  • 22
SivaRajini
  • 7,225
  • 21
  • 81
  • 128
  • possible duplicate of [using jquery, how would i find the closest match in an array, to a specified number](http://stackoverflow.com/questions/3561275/using-jquery-how-would-i-find-the-closest-match-in-an-array-to-a-specified-num) – Anirudh Ramanathan Apr 29 '13 at 07:37

2 Answers2

2

All numbers in Javascript are floating point so this should work just fine:

var theArray = [1940,1941,1943,1945,1978];
var goal = 1944.578895;
var closest = null;

$.each(theArray, function(){
  if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
    closest = this;
  }
});

Source https://stackoverflow.com/a/8584929/390330

Community
  • 1
  • 1
basarat
  • 261,912
  • 58
  • 460
  • 511
  • whether this will work floating point numbers.that means if am having floating point collection as well passing floating point number too. – SivaRajini Apr 29 '13 at 06:50
  • var array=[1945.6777,1978.27555,...] var goal=1944.555 like that whether the above code will work for that. – SivaRajini Apr 29 '13 at 06:52
1

you can use Math.abs

 Math.abs(this - goal) < Math.abs(closest - goal)

Refer this for full example by @Guffa :

using jquery, how would i find the closest match in an array, to a specified number

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307