简体   繁体   English

使javascript数组中的值之间的距离彼此相等

[英]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. 这个大约20到30个值的列表正用于图形中,因此在绘制图形时,如果这些值彼此不同,则图形会上下波动,而不是与每个值一致地上升。 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? 可以使用普通的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. 要获得区间[0,1]中的归一化值,可以使用以下方法:首先获取最小值和最大值,然后调整每个值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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