How can I assign a number to X, if X is in a range of numbers?

Viewed 204

I am working with random and what I want is that if, (for example) X = 173. X must be 10. Let me explain: depending on a range of numbers, X will have a new value:

if X is less than or equal to 10, X must be equal to 26 if X is less than or equal to 20, X must be equal to 35, if X is less than or equal to 30, X must be equal to 12...

Every 10 units X will have a different value So far this is what I have, but I don't think this code is the most appropriate:

var X = 55;

if(X <= 10){
  X = 26;
}else if (X<=20){
  X = 35;
}else if (X <= 30){
  X = 12;
}else if(X <= 40){
  X = 28;
}else if (X <= 50 ) {
  X = 7;
}else if (X <= 60) {
  X = 29
}

console.log(X);

The problem is that if you continue like this, it should do 36 validations (if) I'm working with vanilla JS

1 Answers

Come to think of it, you can do this without any looping at all, still assuming the ranges you provided.

Thanks to @TedHopp for my math error fix!

const values = [26, 35, 12, 28, 7, 29];

var x = 55;

x = x ? (values[Math.ceil(x/10)-1] || x) : values[0];

console.log(x);


original answer

Assuming you actually have ranges of 10, you can use a single array of the potentially assigned values, and iterate the array until you find the range you want.

Like this:

const values = [26, 35, 12, 28, 7, 29];

var x = 55;

for (let i = 0; i < values.length; i++) {
  if (x <= ((i + 1) * 10)) {
    x = values[i];
    break;
  }
}

console.log(x);

Or you can use .find() for this to be a little more succinct.

const values = [26, 35, 12, 28, 7, 29];

var x = 55;

x = values.find((_, i) => x <= ((i + 1) * 10)) || x

console.log(x);

Related