Javascript / jQuery – map a range of numbers to another range of numbers

You can implement this as a pure Javascript function:

function scale (number, inMin, inMax, outMin, outMax) {
    return (number - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}

Use the function, like this:

const num = 5;
console.log(scale(num, 0, 10, -50, 50)); // 0
console.log(scale(num, -20, 0, -100, 100)); // 150

I’m using scale for the function name, because map is frequently associated with iterating over arrays and objects.

Leave a Comment