Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - Convert any array of numbers to an array of proportional values with a max value of 100

If I were to receive an array of numbers, how do I convert the numbers proportionally to the max value 100? For example, the acceptable range of numbers output must be between 0-100

Sorry in advance for any confusion, I am struggling to phrase the question.

Here are some examples to show what I mean:

Input Array: [7000, 500, 0, 850]

Output Array: [70, 5, 0, 8.5]

and

Input Array: [70, 550, 0, 1000]

Output Array: [7, 55, 0, 100]

and

Input Array: [7, 5, 0, 8.5]

Output Array: [70, 50, 0, 85]

To clarify: the output will only be 100 when the max value of the input array is a power of 10.

question from:https://stackoverflow.com/questions/66055644/convert-any-array-of-numbers-to-an-array-of-proportional-values-with-a-max-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Perhaps something as simple as this?

const scaleTo100 = (xs) => {
  const factor = 100 / 10 ** (Math .ceil (Math .log10 (Math .max (...xs))))
  return xs .map (x => x * factor)
}

console .log (scaleTo100 ([7000, 500, 0, 850]))
console .log (scaleTo100 ([70, 550, 0, 1000]))
console .log (scaleTo100 ([7, 5, 0, 8.5]))
.as-console-wrapper {max-height: 100% !important; top: 0}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...