mmclean
mmclean

Reputation: 121

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?

Upvotes: 0

Views: 1195

Answers (2)

xpz
xpz

Reputation: 276

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));

Upvotes: 3

Alan Cheung
Alan Cheung

Reputation: 243

Array.prototype.map() accepts a callback function as its first argument.

It looks like num is not defined as the current element of the array to the callback function scale()

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

Upvotes: 0

Related Questions