Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return value from an array based on input that fits between two steps of another array

I start off with two arrays like this

const colors = ["#00876c", "#50a26f", "#88bb72", "#c1d379", "#fde987", "#fac067", "#f49654", "#e86b4e", "#d43d51"];
const steps  = [13.5, 13.6875, 13.875, 14.0625, 14.25, 14.4375, 14.625, 14.8125, 15];

Both the colors array and steps array have the same length, so you can interpret it as each step associating with the color at the given index.

What I’m trying to do is, based on the value of an input, fit it between the steps and associate said input with its color.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example:

returnColor(13.2) // returns #00876c
returnColor(20)   // returns #d43d51
returnColor(13.7) // returns #50a26f
returnColor(14.5) // returns #fac067

Feel free to ask any question if I haven’t explained quite well.

>Solution :

You can use the closest function from this answer to get the index which is most similar to the input provided.

const colors = ["#00876c", "#50a26f", "#88bb72", "#c1d379", "#fde987", "#fac067", "#f49654", "#e86b4e", "#d43d51"];
const steps  = [13.5, 13.6875, 13.875, 14.0625, 14.25, 14.4375, 14.625, 14.8125, 15];

//get the index of the element which is closest to the step
function closest(num, arr) {
    var curr = arr[0],
        diff = Math.abs(num - curr),
        index = 0;

    for (var val = 0; val < arr.length; val++) {
        let newdiff = Math.abs(num - arr[val]);
        if (newdiff < diff) {
            diff = newdiff;
            curr = arr[val];
            index = val;
        }
    }
    return index;
}

function returnColor(step) {
  const index = closest(step, steps);
  return colors[index];
}

//Tests
console.log(returnColor(13.2)); // returns #00876c
console.log(returnColor(20));   // returns #d43d51
console.log(returnColor(13.7)); // returns #50a26f
console.log(returnColor(14.5)); // returns #fac067
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading