need a little help please for a solution I have an array numbers and 2 vars. if x is greater than any of the array numbers,then y becomes the next number...
var x = 9
var y = 0
var array = [8,12,16,20,24,28,32]
ex
x = 9
y = 12
ex
x = 17
y = 20
ex
is equal...
x = 24
y = 24
CodePudding user response:
Here is a one-line function variable that returns what you want or 0 if no no value in the array is greater than x.
const array = [8 ,12 ,16, 20, 24, 28, 32]
const getY = (x) => (array.find(elem => elem >= x) || 0)
console.log(getY(17)) // 20
CodePudding user response:
Use this function .
`function findY(x,array){
for(var i=0;i<array.length;i )
{
if(x<=array[i]){
y=array[i]
return y
}
}}
findY(x,array)`
CodePudding user response:
Well its not a 1 line function but it does in an easy explanatory way.
var x = 24
var y = 0
var array = [8,12,16,20,24,28,32]
for (let step = 0; step < array.length; step ) {
if(x==array[step]){
y=x
}else if(x>array[step] && step 1 <array.length ){
y = array[step 1];
}
}
console.log(x,y)