简体   繁体   中英

Make the distance between values in javascript array equal between each other

I have a list of numbers inside an array, lets say for example:

var ArrayValues = [1, -2, 3]

This list of around 20-30 values, is being used in a graph, so when the graph is being drawn, if those values are different between each other, the graph goes up and down, not going up consistently with each value. So what I would like is that between each number there is the same amount so that the graph shows a continuous growing line, instead of a line that goes up and down at some points.

Can this be achieved with plain javascript? A function maybe to normalize the values within an array ?

So the above array should be output something like:

var ArrayValues = [0.6, 0, 1];

Making the distance between values more equal between each other.

Thanks !

To get normalized value in the interval [0, 1], you could use the following by first getting min and max values and then adjust every value.

The result is an array with values between zero and one, which keeps relative distances.

 var array = [1, -2, 3], min = Math.min(...array), max = Math.max(...array), result = array.map(a => (a - min) / (max - min)); console.log(result); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM