在 JavaScript 中使数组中的数字相对于 0 – 100 进行变换

javascriptweb developmentobject oriented programming更新于 2025/10/1 17:48:17

假设我们有一个包含一些数字的数组,我们的工作是编写一个函数,该函数接收数组并将所有相对于 0 到 100 的值进行映射。这意味着最大的数字应该被 100 替换,最小的数字应该被 100 替换,所有其他数字应该根据比例转换为 0 到 100 之间的特定数字。

以下是执行相同操作的代码 −

示例

const numbers = [45.71, 49.53, 18.5, 8.38, 38.43, 28.44];
const mapNumbers = (arr) => {
   const max = Math.max(...arr);
   const min = Math.min(...arr);
   const diff = max - min;
   return arr.reduce((acc, val) => acc.concat((100/diff)*(val-min)), []);
};
console.log(mapNumbers(numbers));

输出

控制台中的输出将是 −

[
   90.71688942891859,
   100,
   24.59295261239368,
   0,
   73.02551640340218,
   48.74848116646417
]

相关文章


有用资源