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.
let input = 5 let myarray = [25, 100, 250 ,500] this.myarray.forEach((val, q) => { if(val >= input) { //console.log('Do something here') } });
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,
let input = 5 let myarray = [25, 100, 250 ,500] let index = myarray.findIndex(val => { return val >= input; }); if(index <= -1) { index = myarray.length -1; } console.log(myarray[index]);