Home > other >  how to get element that equal or greater than X but smaller than the next X in array?
how to get element that equal or greater than X but smaller than the next X in array?

Time:09-28

So i want to get a number that greater than X in array but smaller than Y?
example I have array like this:
["5","10","25",etc]
then the value is 5,
so what I want is whenever my value is 5 or greater than 5 but smaller than 10 in array it will only return the 5. like if the value is 6/7/8/9 it will return 5

(Note: The number in array will always different, it's depends on what user set in db)

I have tried with givenNum >= nextNum but it's returning with the number 10 and 25.

any solution?

CodePudding user response:

You could do that :

var array = ["5","10","15","20","25"];
Math.max(...array.filter(nb => nb <= 9))//5
Math.max(...array.filter(nb => nb <= 10))//10

First, you filter the array to keep numbers that are less or equal to the given value. Then you use Math.max() on the filtered array.

CodePudding user response:

I have tried with givenNum >= nextNum but it's returning with the number 10 and 25.

You are comparing strings instead of numbers, string comparison works alphabetically, since "1" comes before "5" alphabetically, "10" comes before "5" which is why "10" < "5" is true.

You need to convert your strings to numbers using Number() then compare.

  • Related