javascriptarraysrescale

How Can I Re-scale An Array To A Range Of Values in Javascript?


I'd like to re-scale a two dimensional array with a function where the min and max input range and min and max output range can be specified. For example, we want to re-scale the values 0 to 8 to 0 to 1.

const scale = (num, in_min, in_max, out_min, out_max) => {
    return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

var array_scaled = orignal_array.map(scale(num, 0, 8, 0, 1));

}

The code produces the following error: ReferenceError: num is not defined

What is the correct syntax to call the scale function from within map?


Solution

  • i guess the argument of map must be a function, i.e. :

    var array_scaled = orignal_array.map(num=>scale(num, 0, 8, 0, 1));