3

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.

2
  • Something like this perhaps - jsfiddle.net/fs4p6330 Commented Apr 11, 2016 at 16:15
  • Yeah, that worked I guess. Can you post this as an answer so I can mark it :D Commented Apr 14, 2016 at 8:46

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.