javascript - Shorten long if else to get element from array based on value -


i have array of 7 values, might or might not extended. have variable foo between 1 , -1. based on foo, select 1 element of array, i'm not happy current solution.

is there preferred way of doing so?

example:

// of course there's useful data in no order alphabet var myarray = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; var foo = myfunc();  // changes between 1 , -1 var index;  if (foo >= 0.1) {     index = 6; } else if (foo < 0.1 && foo >= 0.0) {     index = 5; } else if (foo < 0.0 && foo >= -0.1) {     index = 4; } else if (foo < -0.1 && foo >= -0.2) {     index = 3; } else if (foo < -0.2 && foo >= -0.3) {     index = 2; } else if (foo < -0.3 && foo >= -0.4) {     index = 1; } else {     index = 0; }  var element = myarray[index]; 

thank you!

you use array , array#findindex getting wanted number.

const getindex = v => [-0.4, -0.3, -0.2, -0.1, 0, 0.1, infinity].findindex(a => v < a);    console.log(getindex(-0.5)); // 0  console.log(getindex(-0.4)); // 1  console.log(getindex(-0.3)); // 2  console.log(getindex(-0.2)); // 3  console.log(getindex(-0.1)); // 4  console.log(getindex(0));    // 5  console.log(getindex(0.1));  // 6  console.log(getindex(0.2));  // 6
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -