r3plica
r3plica

Reputation: 13387

range input value check (AngularJS)

So I have a range input control on my page (I am using angularJS). I have set the step as 1 and the max as 10 like this:

<input type="range" step="1" max="10" ng-model="question.score" ng-change="controller.arrangeFilters()" />

Now, the model it is checking can have any number of values up to 10. For example:

var first = [3.333, 6.666, 10],
    second = [2, 4, 6, 8, 10],
    third = [1.666, 3.332, 4.998, 6.664, 8.330, 9.996];

So, when the slider is changed, I need it to check the value and find which number in the array it is closest to. For the first array, if the range value was 1, it would be closest to 3.33. But you could also choose 4 and for the first array that would still be closest to 3.33. The problem is with the second array, if the user chooses 3, it is the same distance between 2 and 4.

So, my question is, is there a function that can check a number between 2 numbers and work out which it is closest to? If possible, I would like it to not return 2 results so that it would pick either 2 or 4 (like rounding) on the second array.

I hope that makes sense.

Upvotes: 3

Views: 638

Answers (1)

Michael Doye
Michael Doye

Reputation: 8171

You can try something like this using reduce

var second = [2, 4, 6, 8, 10],
    userInput = 3;

var closestInt = second.reduce(function (prev, curr) {
  return (Math.abs(curr - userInput) < Math.abs(prev - userInput) ? curr : prev);
});

alert(closestInt); //Output: 2

Upvotes: 2

Related Questions