[JavaScript] 第1430天 使用js写一个方法,使得结果值映射到[0-1]之间(数据归一化)

603 阅读1分钟
// 可以通过以下方式将数值进行归一化
function normalizeValue(value, min, max) {
  return (value - min) / (max - min);
}

其中,value表示原始数据的值,min和max表示数据的范围。这个方法将返回0到1之间的值,即归一化后的值。

const arr = [10, 20, 30, 40];
const min = Math.min(...arr); // 获取数组中的最小值
const max = Math.max(...arr); // 获取数组中的最大值

const normalizedArr = arr.map(value => normalizeValue(value, min, max));
console.log(normalizedArr); // [0, 0.3333333333333333, 0.6666666666666666, 1]
const value = 25;
const min = 0;
const max = 50;
const normalizedValue = normalizeValue(value, min, max);
console.log(normalizedValue); // 0.5

这样,我们就可以将任意范围的数据归一化到0到1之间,方便数据的比较和处理。

更多题目

github.com/haizlin/fe-…