I have below types of array in my vue js. Now I want to find the value key value of match the range. So it’s fall in 25 range so my output should be 25. I tried below code but it always return all the range.
JavaScript
x
8
1
let input = 5
2
let myarray = [25, 100, 250 ,500]
3
this.myarray.forEach((val, q) => {
4
if(val >= input) {
5
//console.log('Do something here')
6
}
7
});
8
Edit:
My input is 5
and it’s fall between 0-25
so I want to get 25
value from my array. Same if my input is 30
it’s fall between 25-100
, in this case I want 100
as value from the array
Advertisement
Answer
You can find the index of the first value that is greater then input. I am assuming the array is sorted,
JavaScript
1
10
10
1
let input = 5
2
let myarray = [25, 100, 250 ,500]
3
let index = myarray.findIndex(val => {
4
return val >= input;
5
});
6
if(index <= -1) {
7
index = myarray.length -1;
8
}
9
10
console.log(myarray[index]);