Reputation: 6512
Suppose I have an array that looks like this:
const points = [ .1, .2, .25, .6, .72, .9 ]
Each of these values represents points/stops along a line. My goal is to have a function which returns the index of the range (the space between two adjacent array values) where an input value falls.
For example if I put in .3
my function would return 3
because .3
is between .25
and .6
and that is the 4th range, as defined by my array. Note that I consider -infinity
to .1
the first (implicit) range.
So far I have come up with this:
function whichRange(input){
if(input < points[0]) {
return 0;
}
else if( input >= points[0] && input < points[1]){
return 1;
}
else if( input >= points[1] && input < points[2]){
return 2;
}
else if( input >= points[2] && input < points[3]){
return 3;
}
else if( input >= points[3] && input < points[4]){
return 4;
}
else if( input >= points[4] && input < points[5]){
return 5;
}
else if (input >= points[5]) {
return 6;
}
}
However this supposes I will always have exactly 6 stops in my array.
What if my array has n
stops. How can I construct a similar, but more general function?
Upvotes: 2
Views: 318
Reputation: 386620
You could use Array#findIndex
and check if the index is found or not, then return the length of the array.
function getIndex(array, value) {
var index = array.findIndex(v => v >= value);
return index !== -1
? index
: array.length;
}
const points = [.1, .2, .25, .6, .72, .9];
console.log(getIndex(points, .3)); // 3
console.log(getIndex(points, .9)); // 5
console.log(getIndex(points, 1)); // 6
Upvotes: 5