1

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

0

1 Answer 1

2

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]);

Sign up to request clarification or add additional context in comments.

2 Comments

Hi in the above solution when there is 0 at the beginning it returns 1 index and when 0 is not at the beginning of the array it returns it returns 0 index. I want index 0 when the 0 present at the beginning of the array
Because it is greater than 0 but less than 25. That is why it returns 25. On the other hand, when 25 is the first index, no item is greater than 5 that is why we are returning the first index.

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.